SlideShare une entreprise Scribd logo
1  sur  15
Geoff Holmes
 Date
 Math
 Weighted Distr
 Strings
 String methods
 Tokenizers
 System
 Examples
Utility Classes (Chapter 17)
import java.util.*;
Department of Computer Science 2
Date
 Represents both times and dates
class Date {
public Date() // current time and date!
public Date(int y, int m, int d, int h, int m, int s)
public int getMonth(), .., getSeconds(),
public int getDay() // day of the week
public int getYear() // year – 1900
public long getTime() // milliseconds since epoch
public void setMonth(int m), .., setSeconds(int s)
Department of Computer Science 3
import java.util.*;
public class DateTest {
public static void main(String [] args) {
Date s = new Date();
System.out.println("s toString = " + s.toString());
int j = 0;
for (int i=0; i<100000; i++) j = j + i;
Date e = new Date();
System.out.println("That took " +
(e.getTime() - s.getTime())+ " msecs");
}
}
Department of Computer Science 4
Math
 Supplies static constants and methods
public static final double E // = 2.71828
public static final double PI // = 3.1415926
 Trigonometric ops (double  double):
sin, cos, tan, asin, acos, atan, atan2
 Rounding ops: ceil, floor, rint, round
 Exponentials: exp, pow, log, sqrt
 Other: abs, max, min, random
Department of Computer Science 5
Draw from weighted distribution
static public int weightedDistribution (int[ ] weights) {
int sum = 0; // sum of weights
for(int i = 0; i < weights.length; i++)
sum += weights[i];
int val = (int) Math.floor(Math.random()*sum+1);
for(int i = 0; i < weights.length; i++) {
val -= weights[i];
if (val < 0) return i; }
return 0; // should never happen
}
 weights (1,3,2) will yield p(0)=1/6, p(1)=1/2, p(2)=1/3
Department of Computer Science 6
String
 Immutable! i.e. cannot be changed
String name = “John Smith”;
char[] data = {‘q’,’e’,’d’};
String quod = new String(data);
 Concatenation: +, but be careful, groups from left:
System.out.println(“Catch-” + 2 + 2)  “Catch22”
System.out.println(2 + 2 + “warned”)  “4warned”
System.out.println(“” + 2 + 2 + “warned”)  “22warned”
// trick: empty leading string
Department of Computer Science 7
String methods
 Will return copies in case of modifications
 Constructors from Strings and StringsBuffer, char
and byte arrays
 concat, replace (characters), (retrieve) substring,
toLowerCase, toUpperCase, trim (whitespace),
valueOf, compareTo, equalsIgnoreCase,
endsWith, startsWith, indexOf, lastIndexOf
Department of Computer Science 8
valueOf safer than toString
public static String valueOf(Object o) {
return (o == null) ? “null” : o.toString();
}
 Purely polymorphic and safe:
Shape aShape = null;
…
String a = String.valueOf(aShape); // “null”
String b = aShape.toString();
// nullPointerException
Department of Computer Science 9
== on Strings
String one = “One”;
String two = new String(one); // copy of one
String three = String.valueOf(one); // ref to one
System.out.println((one == two)); // “false”
System.out.println((one == three)); // “true”
Department of Computer Science 10
StringBuffer
 More like strings in C (arrays of char), can be
modified:
StringBuffer strbuf = new StringBuffer(“hope”);
strbuf.setCharAt(0,’c’);
 Constructors: StringBuffer(String initial),
StringBuffer(int capacity)
 append, insert, and reverse modify buffer and
return this thus allowing for cascaded calls:
strbuf.append(“ with ”).append(“209”);
 setCharAt, charAt,
 length, setLength, ensureCapacity, toString
Department of Computer Science 11
StringTokenizer
 Breaks a string into a sequence of tokens,
 tokens are defined by delimiters (e.g. space)
 Implements the Enumeration protocol
public StringTokenizer(String s)
public StringTokenizer(String s, String delims)
public boolean hasMoreElements()
public Object nextElement()
public String nextToken()
public int countTokens() // remaining tokens
Department of Computer Science 12
StringTokenizer example
public void readLines (DataInputStream input) throws IOException {
String delims = “ tn.,!?;:”;
for(int line = 1; true; line++) {
String text = input.readLine();
if (text==null) return;
text = text.toLowerCase();
StringTokenizer e = new StringTokenizer(text,delim);
while( e.hasMoreElements())
}}
Department of Computer Science 13
Parsing String Values
 For primitive data types wrapper classes provide parsing
from strings and back:
String dstr = “23.7”;
Double dwrap = new Double(dstr);
double dval = dwrap.doubleValue();
 Instead of constructor:
double dval = Double.parseDouble(“23.7”);
enterWord(e.nextToken(), new Integer(line));
 Similar for ints, booleans, longs, and floats
Department of Computer Science 14
System
 Supplies system-wide resources:
 Streams: System.in, System.out, System.err
 System.exit(int) terminates a program
 SystemDemo.java
Department of Computer Science 15
Examples
 Write a program palindrome in two ways:
First, using StringBuffer (and reverse)
• public StringBuffer reverse( )
Second, using
• public char charAt(int index)
 Eliza psychiatric help
 Supply the name of a file as argument and
count the number of lines, words and
characters in the file (tips).

Contenu connexe

Similaire à Utility.ppt

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory archana singh
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdfanupamfootwear
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfanujsharmaanuj14
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 
About java
About javaAbout java
About javaJay Xu
 
Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----Tak Lee
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtractionCharm Sasi
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptxadityaraj7711
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfkokah57440
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerAiman Hud
 

Similaire à Utility.ppt (20)

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
Huraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docxHuraira_waris_Assgnment_4.docx
Huraira_waris_Assgnment_4.docx
 
The Art of Clean Code
The Art of Clean CodeThe Art of Clean Code
The Art of Clean Code
 
About java
About javaAbout java
About java
 
Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
java slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdfjava slip for bachelors of business administration.pdf
java slip for bachelors of business administration.pdf
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 

Plus de BruceLee275640

introductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdfintroductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdfBruceLee275640
 
fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptBruceLee275640
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 

Plus de BruceLee275640 (7)

Git_new.pptx
Git_new.pptxGit_new.pptx
Git_new.pptx
 
introductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdfintroductiontogitandgithub-120702044048-phpapp01.pdf
introductiontogitandgithub-120702044048-phpapp01.pdf
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
 
fdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.pptfdocuments.in_introduction-to-ibatis.ppt
fdocuments.in_introduction-to-ibatis.ppt
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
life science.pptx
life science.pptxlife science.pptx
life science.pptx
 

Dernier

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 

Dernier (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

Utility.ppt

  • 1. Geoff Holmes  Date  Math  Weighted Distr  Strings  String methods  Tokenizers  System  Examples Utility Classes (Chapter 17) import java.util.*;
  • 2. Department of Computer Science 2 Date  Represents both times and dates class Date { public Date() // current time and date! public Date(int y, int m, int d, int h, int m, int s) public int getMonth(), .., getSeconds(), public int getDay() // day of the week public int getYear() // year – 1900 public long getTime() // milliseconds since epoch public void setMonth(int m), .., setSeconds(int s)
  • 3. Department of Computer Science 3 import java.util.*; public class DateTest { public static void main(String [] args) { Date s = new Date(); System.out.println("s toString = " + s.toString()); int j = 0; for (int i=0; i<100000; i++) j = j + i; Date e = new Date(); System.out.println("That took " + (e.getTime() - s.getTime())+ " msecs"); } }
  • 4. Department of Computer Science 4 Math  Supplies static constants and methods public static final double E // = 2.71828 public static final double PI // = 3.1415926  Trigonometric ops (double  double): sin, cos, tan, asin, acos, atan, atan2  Rounding ops: ceil, floor, rint, round  Exponentials: exp, pow, log, sqrt  Other: abs, max, min, random
  • 5. Department of Computer Science 5 Draw from weighted distribution static public int weightedDistribution (int[ ] weights) { int sum = 0; // sum of weights for(int i = 0; i < weights.length; i++) sum += weights[i]; int val = (int) Math.floor(Math.random()*sum+1); for(int i = 0; i < weights.length; i++) { val -= weights[i]; if (val < 0) return i; } return 0; // should never happen }  weights (1,3,2) will yield p(0)=1/6, p(1)=1/2, p(2)=1/3
  • 6. Department of Computer Science 6 String  Immutable! i.e. cannot be changed String name = “John Smith”; char[] data = {‘q’,’e’,’d’}; String quod = new String(data);  Concatenation: +, but be careful, groups from left: System.out.println(“Catch-” + 2 + 2)  “Catch22” System.out.println(2 + 2 + “warned”)  “4warned” System.out.println(“” + 2 + 2 + “warned”)  “22warned” // trick: empty leading string
  • 7. Department of Computer Science 7 String methods  Will return copies in case of modifications  Constructors from Strings and StringsBuffer, char and byte arrays  concat, replace (characters), (retrieve) substring, toLowerCase, toUpperCase, trim (whitespace), valueOf, compareTo, equalsIgnoreCase, endsWith, startsWith, indexOf, lastIndexOf
  • 8. Department of Computer Science 8 valueOf safer than toString public static String valueOf(Object o) { return (o == null) ? “null” : o.toString(); }  Purely polymorphic and safe: Shape aShape = null; … String a = String.valueOf(aShape); // “null” String b = aShape.toString(); // nullPointerException
  • 9. Department of Computer Science 9 == on Strings String one = “One”; String two = new String(one); // copy of one String three = String.valueOf(one); // ref to one System.out.println((one == two)); // “false” System.out.println((one == three)); // “true”
  • 10. Department of Computer Science 10 StringBuffer  More like strings in C (arrays of char), can be modified: StringBuffer strbuf = new StringBuffer(“hope”); strbuf.setCharAt(0,’c’);  Constructors: StringBuffer(String initial), StringBuffer(int capacity)  append, insert, and reverse modify buffer and return this thus allowing for cascaded calls: strbuf.append(“ with ”).append(“209”);  setCharAt, charAt,  length, setLength, ensureCapacity, toString
  • 11. Department of Computer Science 11 StringTokenizer  Breaks a string into a sequence of tokens,  tokens are defined by delimiters (e.g. space)  Implements the Enumeration protocol public StringTokenizer(String s) public StringTokenizer(String s, String delims) public boolean hasMoreElements() public Object nextElement() public String nextToken() public int countTokens() // remaining tokens
  • 12. Department of Computer Science 12 StringTokenizer example public void readLines (DataInputStream input) throws IOException { String delims = “ tn.,!?;:”; for(int line = 1; true; line++) { String text = input.readLine(); if (text==null) return; text = text.toLowerCase(); StringTokenizer e = new StringTokenizer(text,delim); while( e.hasMoreElements()) }}
  • 13. Department of Computer Science 13 Parsing String Values  For primitive data types wrapper classes provide parsing from strings and back: String dstr = “23.7”; Double dwrap = new Double(dstr); double dval = dwrap.doubleValue();  Instead of constructor: double dval = Double.parseDouble(“23.7”); enterWord(e.nextToken(), new Integer(line));  Similar for ints, booleans, longs, and floats
  • 14. Department of Computer Science 14 System  Supplies system-wide resources:  Streams: System.in, System.out, System.err  System.exit(int) terminates a program  SystemDemo.java
  • 15. Department of Computer Science 15 Examples  Write a program palindrome in two ways: First, using StringBuffer (and reverse) • public StringBuffer reverse( ) Second, using • public char charAt(int index)  Eliza psychiatric help  Supply the name of a file as argument and count the number of lines, words and characters in the file (tips).