140 likes | 328 Views
Simple I/O. A Scanner Darkly. Why?. Output is easy System.out.println() Input is hard in java System.in() does not have great methods for input. Scanner class. Part of the util package import java.util.Scanner; How to create one Scanner in = new Scanner(System.in);.
E N D
Simple I/O A Scanner Darkly
Why? • Output is easy • System.out.println() • Input is hard in java • System.in() does not have great methods for input
Scanner class • Part of the util package • import java.util.Scanner; • How to create one • Scanner in = new Scanner(System.in);
Useful Scanner methods • next() • nextInt() • nextDouble()
Scanner Example import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { System.out.print(“Enter your name> "); Scanner in = new Scanner(System.in); String name = in.next(); System.out.println("Hello " + name); } }
Keep In Mind • White space (spaces, tabs, newlines) separate input values • It is nice to provide the user with a prompt • Otherwise they’ll be won’t know they have to input something.
printf • Similar to print and println • System.out.printf() • For formatting output • Adding $ signs • Rounding numbers • Creating columns with a given width
How Do I Use printf • Two arguments • Formatting String • %[flags][width][.precision]conversion • String to format and print • Example • System.out.printf("%.2f", 5.246565);
Conversion Tags • You must include it at the end • s – Strings • Ex. printf(“%s”, “Sam”) • d – ints • printf(“%d”, 5182) • f – doubles • printf(“%f”, 2.123456)
Flags • , - add ,’s to big numbers • System.out.printf(“%,d”, 12345678) -> 12,345,678 • ( - add parentheses around negative numbers • System.out.printf(“%,(d”, 12345678) -> 12,345,678 • System.out.printf(“%,(d”, -12345678) -> (12,345,678)
Width • Number of characters • Default is right aligned • Use – for left align • Example • System.out.printf(“%-10s”, “Soda”); • System.out.printf(“%10.2f”, 10.25); • Soda 10.25
More about Width • Special characters count as characters • System.out.printf(“%11s”, “Price:\n”); • If you want 10 spaces, you would use 11 because the \n counts as one
Precision • How many spaces to take up • . and then the number of spaces • Examples: • System.out.printf(“%.2s”, “Hello”) -> He • System.out.printf(“%.10s”, “Hello”) -> Hello • System.out.printf(“%.5f”, Math.PI) -> 3.14159 • System.out.printf(“%.4f”, Math.PI) -> 3.1416 • System.out.printf(“%f”, Math.PI) -> 3.141593
Multiple arguments to printf • System.out.printf(“%10s %10.2f”, “Total:”, mySum); • Is the same as • System.out.printf(“%10s”, “Total:”); • System.out.printf(“%10.2f”, mySum);