当我们在编写Java程序时,想要录入一个int型的数值,并在其下方录入一个字符串类型的值。
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
// Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
Scanner sc = new Scanner(System.in) ;
System.out.print("请输入一个人数字:");
int num = sc.nextInt();
System.out.print("请输入一个字符串:");
String str = sc.nextLine();
System.out.println("num = " + num);
System.out.println("str = " + str);
}
}
- 程序运行后我们在控制台输入了数值
1
,按下回车键表示输入结束,准备去输入字符串的值,结果程序直接结束了。看输出结果,num = 1
str =
也就是说num和str我们都进行录入了,但是明明没有输入字符串值。
- 这是因为在我们按下回车键结束数字输入时,由于回车键是
\r\n
,属于字符串,而下面要录入的也刚好是字符串,系统就默认将\r\n
给了str
,而nextLine()
方法解结束符也恰好为回车符,所以结束了字符串的输入。得到最后的结果就是num = 1 ; str = "" ;
当然不单单是nextInt()方法会对nextLine()方法有影响,nextByte()、nextDouble()、nextBoolean()等以\r\n
作为结束符的Scanner类中的方法都会对其产生影响
将str的录入移到num的上面
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
// Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
Scanner sc = new Scanner(System.in) ;
System.out.print("请输入一个字符串:");
String str = sc.nextLine();
System.out.print("请输入一个人数字:");
int num = sc.nextInt();
System.out.println("num = " + num);
System.out.println("str = " + str);
}
}
创建不同的Scanner对象录入基本数据类型和字符串类型
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
// Scanner类中的nextInt()方法和nextLine()方法连用时所出现的问题
Scanner sc = new Scanner(System.in) ;
System.out.print("请输入一个人数字:");
int num = sc.nextInt();
Scanner sc1 = new Scanner(System.in) ;
System.out.print("请输入一个字符串:");
String str = sc1.nextLine();
System.out.println("num = " + num);
System.out.println("str = " + str);
}
}