在Java循环中多次使用扫描仪

问题描述 投票:0回答:1

我是新手,我正在尝试编写将用户输入存储在长度为[[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
java
1个回答
0
投票
问题是您没有在while循环内进行扫描。您需要以扫描整数的方式扫描单词。您没有使用d.next(),而是使用了d.toString()

请执行以下操作:

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); } } }

示例运行:

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
此外,请注意,我只使用了Scanner的一个实例。您不需要Scanner的两个实例。您可以在程序的任何地方重用Scanner的相同实例。
© www.soinside.com 2019 - 2024. All rights reserved.