Chapter 2 Helper Sheet
Scanner object knows: How to read from the screen
Package to import: import java.util.Scanner;
How to create a Scanner for your screen:
- Scanner xxx = new Scanner(System.in);
How to use a Scanner to read from your screen:
- int value1 = keyb.nextInt();
Methods that work on Scanner:
- nextInt()
- nextLong()
- nextByte()
- nextDouble()
- next() up to next whitespace (delimiter)
- nextLine() up to \n
- useDelimiter()
NumberFormatter object knows: How to print money
Package to import: import java.text.NumberFormat;
How to create a NumberFormatter for your money:
- NumberFormat moneyFormatter = NumberFormat.getCurrencyInstance();
How to use a NumberFormatter to print to your screen:
- System.out.println(I bought it for + moneyFormatter.format(cost))
DecimalFormatter object knows: How to print decimals
Package to import: import java.text.DecimalFormat;
How to create a DecimalFormatter for your numbers:
- DecimalFormat percentage2 = new DecimalFormat(0.00%);
How to use a DecimalFormatter to print to your screen:
- System.out.println(percentage2.format(.308)); // will print 30.80%
Different format options:
- 0 = required position
- # = show it if you have it
- % = make it a % (mult by 100)
- E = E notation (scientific)
printf command:
Just like println, but uses variables inside string start % and end character.
%, then size of whole number, then decimal places and then type
- d = int
- f = float
- s = string
- c = char