在循环Java中多次使用scanner
我是这方面的新手,我正在尝试编写一个代码,将用户输入存储在一个长度为n的数组中(长度也由用户决定)。 因此,我决定使用在循环Java中多次使用scanner,java,Java,我是这方面的新手,我正在尝试编写一个代码,将用户输入存储在一个长度为n的数组中(长度也由用户决定)。 因此,我决定使用while循环来使用扫描器n次,这样每次用户都可以随着循环的进行在该位置存储字符串 但是当我运行代码时,它只打印语句,不允许我(或用户)输入字符串 public static void main(String[] args) { String[] contadores; Scanner cont= new Scanner(System.
while
循环来使用扫描器
n次,这样每次用户都可以随着循环的进行在该位置存储字符串
但是当我运行代码时,它只打印语句,不允许我(或用户)输入字符串
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++;
}
正如您看到的,它没有给我足够的时间来输入一些东西,我不知道它是JDK(我想不是),还是因为它在main
中,我尝试使用Thread.sleep(4000)代码>但输出为错误未处理的异常类型InterruptedException
问题在于,您没有在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);
}
}
}
另外,请注意,我只使用了Scanner
的一个实例。您不需要两个扫描仪的实例。您可以在程序中的任何地方重复使用相同的扫描仪实例。问题在于,在循环时,您没有在内部进行扫描。您需要以扫描整数的方式扫描单词。您使用的不是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);
}
}
}
另外,请注意,我只使用了Scanner
的一个实例。您不需要两个扫描仪的实例。您可以在程序中的任何地方重复使用相同的Scanner
实例。使用相同的Scanner
var,不需要创建新的d
。使用相同的Scanner
var,不需要创建新的d
。是的,如果您有一些关于原因的文献,它是有效的。next()有效并且.toString()在这种情况下,这会很有帮助。我认为是关于“吃”和\n空间的。“但这对我来说不太清楚。”@josefisa-我错过了你的评论。方法,是一个来自的方法,它返回一个字符串
,而不是像这样阻塞并等待输入扫描。我希望,这会有帮助。是的,如果你有一些关于为什么的文献,它是有效的。next()有效,.toString()无效。在这种情况下,它会非常有用。我认为是关于“吃”和\n空间的。“但这对我来说不太清楚。”@josefisa-我错过了你的评论。方法,是一个来自的方法,它返回一个字符串
,而不是像这样阻塞并等待输入扫描。我希望,这会有帮助。
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