1.下面兩段程序,第二段有問題,為什么第一段沒問題?
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個字符串:");
String str1 = sc.nextLine();
System.out.println("請輸入第二個字符串:");
String str2 = sc.nextLine();
System.out.println("str1 = "+ str1 +"," + "str2 = "+ str2);
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個數(shù)字:");
int num1 = sc.nextInt();
System.out.println("請輸入第一個字符串:");
String str3 = sc.nextLine();
System.out.println("num1 = "+ num1 +"," + "str3 = "+ str3);
原因:因為nextLine();輸入字符串時,遇到\r\n,就會結(jié)束讀取,但是不讀取\r\n。在第二段程序中,輸入一個數(shù)字后按回車,數(shù)字賦值給num1后nextInt()讀取結(jié)束。后邊nextLine();遇到回車(\r\n)也就結(jié)束讀取。怎樣解決?
常用方法:輸入都使用.nextLine();后邊使用方法使字符串轉(zhuǎn)數(shù)字,如下:
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個數(shù)字:");
String str1 = sc.nextLine();
int num1 = Integer.parseInt(str1);
System.out.println("請輸入第一個字符串:");
String str2 = sc.nextLine();
System.out.println("num1 = "+ num1 +"," + "str2 = "+ str2);
2.在使用Scanner輸入整數(shù)時可以使用,一個方法先判斷是否輸入是整數(shù):
Scanner sc = new Scanner(System.in);
int num = 0;
System.out.println("請輸入整數(shù):");
if(sc.hasNextInt()){
num = sc.nextInt();
}