where will we read data from?
public static void main(String[] args) {
/*we have this 'Scanner' class that's defined in 'java.util' package.*/
/*where will we read data from?*/
/*Terminal window || file*/
Scanner scanner = new Scanner(System.in);
/*call the 'nextByte' method, see what we get.*/
byte age = scanner.nextByte();
/*print it on the terminal.*/
System.out.println("You are " + age);//implicit casting.
/*run the program,and see what happens*/
}
result
21
You are 21
but this’s pretty boring,let’s add a label here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
/*before reading data,we gonna call the 'println' method and say something. */
System.out.println("Age: ");
byte age = scanner.nextByte();
/*but this's pretty boring,let's add a label here*/
System.out.println("You are " + age);
/*run the program,and see what happens*/
}
result
Age:
21
You are 21
System.out.println("Age: ");// add a newline after the label.
/*To solve this issue, we call the 'print' method */
result
Age: 21
You are 21
what if we type a floating number?
result
Age: 21.1
Exception in thread "main" java.util.InputMismatchException
reason&solution
/*because this method - 'nextByte()' can only parse byte values.*/
/*if we want to get a floating number,
we need to call the 'nextFloat()' method.
*/
float age = scanner.nextFloat();
result
Age: 21.5
You are 21.5
what if we want to read a string?
String name = scanner.next();
result
Name: shengmin
You are shengmin
this time I gonna type my full name:
Shengmin Zhang
Name: Shengmin Zhang
You are Shengmin
Well,we don’t get the last name.
Here’s the reson.
- every time we cal the method ‘next()’, it reads one token.
- here we have a space
so we need call the ‘nextLine()’ method.
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.println("You are " + name);
Name: Shengmin Zhang
You are Shengmin Zhang
- this
nextLine()
method returns a string, - and we store it in the ‘name’ variable.
what if I type a few spaces before my name?
let’s see what happens
Name: Shengmin Zhang
You are Shengmin Zhang
- this looks like a little odd.
- this’s where we use the
trim()
method. - we can get rid of the all white spaces before or after a string.
System.out.print("Name: ");
String name = scanner.nextLine().trim();
System.out.println("You are " + name);
Name: Shengmin Zhang
You are Shengmin Zhang
- just before storing the result,
- here we can use the ‘dot’ operator to access the members of this string object .
- so we call the ‘trim()’ method,and then store the result.