[英]Using scanner various times in a loop Java
I'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).我是新手,我正在尝试编写一个代码,将用户输入存储在一个长度为n的数组中(长度也由用户决定)。 So I decided to use a
while
loop to use Scanner
n times, so that each time the user could store an String
in that location as the loop advances.所以我决定使用
while
循环来使用Scanner
n次,这样每次用户都可以在循环前进时将String
存储在该位置。
But when I run the code, it just prints the statements don't letting me (or the user) to input the String
.但是当我运行代码时,它只会打印不允许我(或用户)输入
String
的语句。
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:当我运行它时,output 是:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main
, I tried using Thread.sleep(4000);
如您所见,它没有给我足够的时间输入内容,我不知道它是 JDK(我认为不是),还是因为在
main
内部,所以我尝试使用Thread.sleep(4000);
but the output is an error Unhandled exception type InterruptedException
.但是 output 是一个错误
Unhandled exception type InterruptedException
。
The problem is that you are not scanning inside the while
loop.问题是您没有在
while
循环内进行扫描。 You need to scan the words the way you have scanned the integer.您需要按照扫描 integer 的方式扫描单词。 Instead of using
d.next()
, you've used d.toString()
.您没有使用 d.next
d.next()
,而是使用了d.toString()
。
Do it as follows:执行以下操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:示例运行:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner
.另外,请注意,我只使用了一个
Scanner
实例。 You do not need two instances of Scanner
.您不需要两个
Scanner
实例。 You can reuse the same instance of Scanner
everywhere in your program.您可以在程序中的任何地方重复使用相同的
Scanner
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.