有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java循环中多次使用scanner

在这方面我是新手,我正在尝试编写一个代码,将用户输入存储在n长度的数组中(长度也由用户决定)。 所以我决定使用while循环来使用Scannern次,这样每次用户都可以随着循环的进行在该位置存储一个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) 个答案

  1. # 1 楼答案

    问题是您没有在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实例