1. Java.util.Scanner可以用来从键盘获取输入
Scanner.next() 只能读取字符,遇到任何的符合都不会输出
Scanner.nextLine() 会完全按照用户输入的string输出
Example1 for Scanner.next():
package com.mengdd.junit;
import java.util.*;
public class ScanDemo {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);//get data from keyboard
//get date with nextline
System.out.println("get date with next: ");
if (scan.hasNext()){
String str = scan.next();
System.out.print(str);
}
}
}
run this class and input: I am entering a line to test
after running, the output would be:
get date with next:
I
All strings after I will not be outputed
Example 2 for Scanner.nextLine():
package com.mengdd.junit;
import java.util.Scanner;
/**
* Created by Sandy.Liu on 2017/6/22.
*/
public class ScanDemo1 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("please enter a string");
if(scan.hasNextLine()){
String str = scan.nextLine();
System.out.print(str);
}
}
}
run this class and the result will be:
please enter a string
hellow i am entering a line to test
hellow i am entering a line to test
Process finished with exit code 0
So nextLine() will get every single character the user inputs even the punctuation