對於Java編程而言是新的。我只想打印由用戶輸入的n個字符串,其中「n」是由用戶輸入的測試用例的數量。所以下面是我的代碼...但nextLine()方法在基本情況下(即在int i=0
)沒有從用戶處獲得輸入。 代碼java.util.scanner方法不在for循環中的基本情況下執行?
import java.util.Scanner;
import java.io.InputStreamReader;
public class Stringprint{
public static void main(String[] args){
String str;
int testcase;
Scanner scanIn = new Scanner(System.in);
System.out.println("Enter the number of testcases :");
testcase = scanIn.nextInt();
for(int i = 0; i < testcase ; i ++){
System.out.println("Enter the String" + i + ":");
str = scanIn.nextLine();
System.out.println(string);
}
}
}
出來放上面的代碼也越來越像:
Enter the number of testcases :
4
Enter the String0:
Enter the String1:
hello
hello
Enter the String2:
hai
hai
Enter the String3:
bye
bye
所以我在哪裏得到wrong..why它不是在i=0
要求輸入字符串?我在這裏做錯了什麼?
問題歸結於nextLine()。使用next(),它會正常工作.. –
使用next(),nextInt()或其他nextFoo()方法後跳過nextLine()的可能重複(http://stackoverflow.com/questions/13102045/ skip-nextline-after-using-next-nextint-or-other-nextfoo-methods) – resueman
This may clear:http://stackoverflow.com/a/20190113/5188230 –