java的Scanner类可以用来接收键盘输入的数据。next()和nextLine()方法用来接收字符串,next()方法接收字符串时遇到空格或回车结束输入,而nextLine()方法可以接收空格,最后输入回车才结束。下面用实例演示两者的区别:
next()方法:
package scanner;
import java.util.Scanner;
public class Scan {
public static void main(String[] args) {
String a,b;
Scanner sc=new Scanner(System.in);
System.out.println("next()方法接收字符串:");
a=sc.next();
System.out.println(a);
}
}
运行结果截图:
nextLine()方法:
package scanner;
import java.util.Scanner;
public class Scan {
public static void main(String[] args) {
String a,b;
Scanner sc=new Scanner(System.in);
System.out.println("nextLine()方法接收字符串:");
b=sc.nextLine();
System.out.println(b);
}
}
运行结果截图:
两个方法一起用可能会出错:
package scanner;
import java.util.Scanner;
public class Scan {
public static void main(String[] args) {
String a,b;
Scanner sc=new Scanner(System.in);
System.out.println("next()方法接收字符串:");
a=sc.next();
System.out.println(a);
System.out.println("nextLine()方法接收字符串:");
b=sc.nextLine();
System.out.println(b);
}
}
运行结果截图:
这时程序已结束运行,不能再输入。原因是next()方法遇到回车结束输入,却把最后的回车符留给了nextLine(),nextLine()方法接收了一个空字符串。
解决方法是next()方法后面再加一个nextLine()用来接收回车符,代码如下:
package scanner;
import java.util.Scanner;
public class Scan {
public static void main(String[] args) {
String a,b;
Scanner sc=new Scanner(System.in);
System.out.println("next()方法接收字符串:");
a=sc.next();
System.out.println(a);
a=sc.nextLine();//接收回车符
System.out.println("nextLine()方法接收字符串:");
b=sc.nextLine();
System.out.println(b);
}
}
运行结果截图: