我试图从用户那里获得n行输入(字符串)
问题在于它总是意味着
有什么问题?
Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt();
// initialize input array
String[] longWords = new String[lines] ;
//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
longWords[i] = sc.nextLine() ;
}
答案 0 :(得分:3)
这样做:
Scanner sc = new Scanner(System.in);
//how many lines should be taken
int lines = sc.nextInt();
//read the carret! This is, the line break entered by user when presses Enter
sc.nextLine();
// initialize input array
String[] longWords = new String[lines] ;
//set the input from the user into the array
for (int i = 0; i < longWords.length; i++) {
longWords[i] = sc.nextLine() ;
}
答案 1 :(得分:0)
问题是nextInt()
不会在输入行的末尾处理换行符,因此当您输入1时,Scanner
会看到'1',\ n',但是只接受'1'。然后,当您调用nextLine()
时,它会看到剩下的换行符,然后立即返回。这是一个很难找到的错误,但只要记住换行符是否还在等待处理。