100 likes | 162 Views
Learn about formatted output using the printf method and comparing strings' lexicographic ordering in Java programming.
E N D
Introduction to Programming Java Lab 4: Formatted Output and Strings JavaLab4 lecture slides.ppt Ping Brennan (Ping.Brennan@gmail.com) 31 January 2014
Java Project Project Name: JavaLab4 FormattedOutput LexicographicOrdering
Class FormattedOutput • Objectives • Using the printf method to specify how values should be formatted. • Applying formatted output in a program. • Format types Decimal integer - use %nd n: the width of field in characters d: decimal Floating point - use %r.sf r: the width of field in characters s: the number of digits after the decimal point f: fixed floating point
Class FormattedOutput (2) • Use a format specifier of the form %nd to print out the numbers a1, b1, c1, d1 in the following way: What’s the value of n (i.e. the width of the field) for this problem?
Class FormattedOutput (3) • Next use a format specifier of the form %r.sf to print out the numbers a2, b2, c2, d2 in the following way: What’s the value of r? What’s the value of s?
Anatomy of Class FormattedOutput public class FormattedOutput { public static void main(String[] args) { // initialise the following variables int a1 = 28, b1 = 418, c1 = -89, d1 = -3007; double a2 = 28.467, b2= -1.2, c2 = 0.0145, d2 = 587.2; System.out.printf("a1:%?d\n", a1); // Write more Java code to print out b1, c1, and d1 System.out.printf("a2:%?.?f\n", a2); // enter the ? values // Write more Java code to print out b2, c2, and d2 } } insert the correct value for ?
Class LexicographicOrdering • Objectives • Use compareTo() method to compare the lexicographic ordering of two strings. • Understand the relational operators for comparing strings. • compareTo() method • Relational operators < , <= , > , >= , == , !=
Lexicographic Ordering of Strings • Dictionary order • Java lexicographic ordering: • Uppercase letters precede lower case letters • Numbers precede letters • The space character precedes all printable characters
Anatomy of Class LexicographicOrdering public class LexicographicOrdering { public static void main(String[] args) { // Declare String variables a1, a2, ..., a9 and b1, ..., b9 String a1 = "Tom", b1 = "Jerry", a2 = "Tom", b2 = "Tomato"; // The statement below compares string a1 with string b1. // It prints a Boolean value true if string a1 precedes // string b1 in lexicographic order or if a1 is equal to b1. // Otherwise the Boolean value false is printed. System.out.println(a1.compareTo(b1) <= 0);
Anatomy of Class LexicographicOrdering (2) System.out.println(a2.compareTo(b2) <= 0); /* Continue in the same way as above to print * out the remaining 7 Boolean values for the * given pairs of strings. */ } // end of main method } // end of class LexicographicOrdering