Scanner Basics:
-
Scanner is an API added in Java 1.5
-
Used to manage input
-
Need to import before use
-
First step is to create a Scanner object that will manage all inputs:
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //read keyboard input
}
}
-
Can read data from multiple sources
-
Stream of data connects program to keyboard
-
Input is System.in/standard in
-
Then we can use Scanner to read each chunk, or token of data.
-
To split the input into tokens, a delimiter is used
- Default delimiter is whitespace, but can be changed to anything
-
Different token types for different variable types:
- nextInt ⇒ int
- nextDouble ⇒ double
- next ⇒ String
- nextLine ⇒ String until newline character is reached
-
-
Scanner Errors:
-
Error if token type is not in stream
-
can append ‘has’ to any normal scanner method
- Checks to see whether token type is in stream
Multiple Prompts and Tokens:
-
After inputting user input, a newline character is leftover
-
Only execption is nextLine, which removes it
-
This is inputted to the next user input prompt
-
Ex. if user inputs 5 then 9, Scanner sees ‘5’, ‘/n9/n’
-
This is not a problem unless nextLine is being used
- Add extra nextLine prompt before the actual one
-
-
Multiple Tokens Per Line:
-
You can input mutiple tokens in a single call
- Any leftover data is left in the stream
-
Can get data for two next methods from one input:
-
Ex.
-
Input = 78 Monday
-
nextInt = 78, leaves behind ’ Monday/n’
-
next = Monday
-
Doesn’t wait for user input as data is already in stream
-
nextLine would’ve also taken the space before Monday
-
-
-
-
We can remove any spaces using the ‘.trim()’ method
Packages:
-
Classes can be grouped together based on the functions they provide
- These are called packages and each have a name
-
Built-in Java classes are part of a package called java.lang
-
To use classes not in the java.lang package, you must import them:
import java.util.Scanner; //imports just scanner
import java.util.*; //imports all util packages
-
Dot seperation is like hierarchy/directories
- Packages can house subpackages
-
Using wildcard(*) to import multiple classes can cause problems
-
It’s possible for two packages to have the same name
- To fix, only import the packages you need (don’t use *)
-
Can create larger compile times
- Generated bytecode is the same either way
-
Formatting with printf:
- Example format:
System.out.printf(formatString, values); //Format
//Actual Example:
System.out.println(day + " Celsius: " + celsius);//Normal
System.out.printf("%s Celsius: %f\n", day, celsius);//Printf
System.out.printf("%s Celsius: %f\n", celsius, day);//This would result in an error
-
In this example, the fixed part is “Celsius” and variables are day and celsius
-
%f and %s are format placeholders
-
Format = %[flag][width][.precision]type
-
Format placeholders must start with % to show they aren’t part of the String
-
Some format placeholder types:
- Decimal ⇒ %d
- float ⇒ %f
- String ⇒ %s
-
Must specify the actual paramters in the same order as the placeholders (Ex above)
-
Reduce decimal places:
- Add the decimal place in front of the ”%”
-
System.out.printf("%s Celsius: %0.1f\n", day, celsius);//Print value to 1 decimal
- Change width/alignment of values:
//Will print var celcius with a width of 10 (extra space will be whitespace)
System.out.printf("%10s Celsius: %f\n", day, celsius); //Padding before string
System.out.printf("%-10s Celsius: %f\n", day, celsius); //Padding after string
- Add thousand’s seperator:
//would print for example 100,543 instead of 100543
System.out.printf("%s Celsius: %,f\n", day, celsius);//comma in front of f
String.format:
- Same as printf but values can be stored to a String instead of printing
NumberFormat (currency formatting):
- Import the package, then create NumberFormat object, then print using one:
//Import
import java.text.NumberFormat;
//Create number
int total = 5;
//Create object
NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();//Local currency
NumberFormat currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE);//Specific Locale(France)
//Print
System.out.println ("Formatted Total: " + currencyFmt.format(total));
DecimalFormat:
import java.text.DecimalFormat;
public class DecimalFormatDemo {
public static void main(String[] args) {
DecimalFormat formatter1 = new DecimalFormat("0.0");
DecimalFormat formatter2 = new DecimalFormat("00.00");
DecimalFormat formatter3 = new DecimalFormat(".00");
DecimalFormat formatter4 = new DecimalFormat("0.00%");
System.out.println("0.0: " + formatter1.format(.8675309));
System.out.println("00.00: " + formatter2.format(.8675309));
System.out.println(".00: " + formatter3.format(.8675309));
System.out.println("0.00%: " + formatter4.format(.8675309));
System.out.println(".00: " + formatter3.format(8675309));
}
}