在Java循环中多次使用scanner
在这方面我是新手,我正在尝试编写一个代码,将用户输入存储在n长度的数组中(长度也由用户决定)。
所以我决定使用while
循环来使用Scanner
n次,这样每次用户都可以随着循环的进行在该位置存储一个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++;
}
当我运行它时,输出是:
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
正如你看到的,它没有给我足够的时间来输入一些东西,我不知道它是JDK(我认为不是),还是因为它在main
内,我尝试使用Thread.sleep(4000);
,但输出是错误的Unhandled exception type InterruptedException
# 1 楼答案
问题是您没有在
while
循环内扫描。你需要像扫描整数一样扫描单词。您没有使用d.next()
,而是使用了d.toString()
按如下方式操作:
运行示例:
另外,请注意,我只使用了
Scanner
的一个实例。您不需要两个Scanner
实例。您可以在程序中的任何地方重用相同的Scanner
实例