80 likes | 315 Views
Review . Chapter 2-5 and 4-1. Class string methods. public int compareTo ( String anotherString ):
E N D
Review Chapter 2-5 and 4-1
Class string methods public intcompareTo(StringanotherString): returns the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument. public booleanequals(ObjectanObject): return true if the String are equal; false otherwise. public StringreplaceFirst(Stringregex, String replacement): Replace only the first occurrence of a string regx with a replacement string. public StringreplaceAll(Stringregex, String replacement): Replace all occurrences of a string regx with a replacement string.
printf • format specifier: %n, %s, %c, %d, %f. • Width: an integer number number of columns. • Precision: number of decimal points (ex: .2) this allowed for %f • By default, the alignment of reserved columns from right to left else write %-width (minus) • By default, the alignment of the system output from left to right. • We can combine between all of them in a single printf statement. ex: %5.2f, %4d,%.2f,%10s,%c.
public class Program1 { public static void main(String []args ) {int n; double x; String s = "Java Programming Quiz1" ,s1; n= s.indexOf('a',5); s1 = s.substring( 5 , 16 ); x= n * 5.0 + 2 * ++n; System.out.printf("s= %-25s%ns1= %12s%nx= %6.2f%n", s ,s1,x ); }} Check the model answer
public class Program1 { public static void main(String []args ) { double y; inti=2; String s = "good morning girls" ,s1,s2; s1= s.replace('o','*'); s2 = s.substring( 13 , 18 ).toUpperCase(); y= 5.0 / i + 4 * ++i; System.out.printf("s= %-25s%ns1= %25s%ns2= %10s%n y= %6.2f%n", s ,s1,s2,y ); }} Check the model answer
public class Program1 { public static void main(String []args ) {inti=2, n; n= ++i* ++i; System.out.printf(“i= %6d, n=%-6d%n“,i,n); }}
If statement Write a program that read your age then print the appropriate message (child, young, wise or old):
Switch statement switch (alpha%10){ case 0: case 1: alpha = alpha+2; break; case 2: alpha++; case 3: alpha= 2* alpha; default: alpha--; }System.out.println("alpha= " + alpha); Consider alpha=11,5,44, or 63