Java中的Scanner包中的next()、nextLine()、nextInt()都是用来读取输入的方法,但它们之间存在一点细微的区别,这里我们一一举例说明:
首先总结一下:主要区别在于对空格的处理方式不同。
next()方法:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("使用next()方法,输入为:");
while(sc.hasNext()){
String val=sc.next();
System.out.println("输出为:");
System.out.println(val);
}
}
}
运行结果:
从上可知:使用next()方法读取输入时是将空格作为两个字符串之间的间隔来处理。
nextLine()方法:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner sc=new Scanner(System.in)