[英]How do you take multiple user inputs of different data types within a for loop in Java?
I'm trying to prompt the user to type in a string, which will be stored in an array of strings, followed by an inputted int which will be placed into an int array.我试图提示用户输入一个字符串,该字符串将存储在一个字符串数组中,然后是一个输入的 int,该 int 将被放入一个 int 数组中。
I'm running into a problem where the first line is printed, but the user isn't prompted to type in a string.我遇到了打印第一行的问题,但没有提示用户输入字符串。 Then the second print statement is immediately printed, and the user is only able to type in an int.然后立即打印第二个打印语句,用户只能输入一个整数。
So far I have:到目前为止,我有:
int i, n = 10;
String[] sentence = new String[1000];
int[] numbers = new int[1000];
for(i = 0; i < n; i++)
{
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = scan.nextLine();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = scan.nextInt();
}
As output I get:作为输出,我得到:
Enter String 1:
Enter int 1:
Here you can input an int, and it is stored into the int array.在这里你可以输入一个int,它被存储到int数组中。 But you can't input a String for the String array.但是您不能为字符串数组输入字符串。
Ples help.请帮忙。
Put scan.nextLine() like this: 像这样放置scan.nextLine():
for(i = 0; i < n; i++){
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = scan.nextLine();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = scan.nextInt();
scan.nextLine();
}
This problem is caused because of nextInt()
method. 此问题是由于nextInt()
方法引起的。
Whats happening here is that nextInt()
method consumes the integer entered by the user but not the new line character at the end of the user input which is created when you press enter key. 这里发生的是, nextInt()
方法使用用户输入的整数,但不使用在按Enter键时创建的用户输入末尾的换行符。
So when you press enter after inputting an integer, next call to nextLine()
consumes the new line character which wasn't consumed in the last iteration of the loop by nextInt()
method. 因此,当您在输入整数后按Enter键时,对nextLine()
下一次调用将使用nextLine()
,而nextInt()
方法在循环的最后一次迭代中不会使用该换行符。 That's why it skips the input of String
in the next iteration of the loop and does't waits for the user to input a String
这就是为什么它在循环的下一个迭代中跳过String
的输入并且不等待用户输入String
Solution 解
You can consume the new line character by calling nextLine()
after the nextInt()
call 您可以在nextInt()
调用之后调用nextLine()
来消耗nextLine()
for(i = 0; i < n; i++)
{
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = scan.nextLine();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = scan.nextInt();
scan.nextLine(); // <------ this call will consume the new line character
}
Use sc.next();使用 sc.next(); instead of sc.nextLine();而不是 sc.nextLine(); if not able to enter string value in first iteration.如果无法在第一次迭代中输入字符串值。
Scanner sc = new Scanner(System.in);
for(i = 0; i < n; i++);
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = sc.next();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = sc.nextInt();
sc.nextLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.