在 Java 中多次从标准输入中读取

Read from standard input several times in Java

我已经为此苦苦挣扎了一段时间,虽然我认为这真的很简单哈哈。

一点背景信息:我正在制作一个小程序来自动回答网络调查(使用 Selenium WebDriver)。每个调查都在用户名和密码下完成。我的目标是我的程序用他们的 ID 问我问题(比如 ID1:___、ID2:____ 等),并为每个用户+pass 做这个。

我创建了一个方法来从文本文件中获取用户和密码并将它们保存到字符串列表 [2] 中。

    // Just a test list with the name (or id) of each question
    List<String> nombrePreguntas = new LinkedList<String>(Arrays.asList("nombre1", "nombre2", "nombre3", "nombre4"));

    // read users from file -> usuarios[0] = user, usuarios[1] = pass.
    List<String[]> usuarios = leerUsuarios("entrada.txt");

    for (String[] u : usuarios) {
        // print each user and pass
        System.out.println(u[0] + " - " + u[1]);
        // for each user+pass, read the questions and ask for their answer in stdin
        List<Integer> respuestas = leerRespuesta(nombrePreguntas);
        System.out.println(respuestas );
    }

这只对第一个用户有效一次。该程序要求回答 4 个问题,然后打印出答案。之后,它只打印 user+pass 以及每个问题的名称和一个空的答案数组,如下所示:

usuario1 - pass1
nombre1: 1
nombre2: 2
nombre3: 3
nombre4: 4
[1, 2, 3, 4]
usuario2 - pass2
nombre1: nombre2: nombre3: nombre4: []
usuario3 - pass3
nombre1: nombre2: nombre3: nombre4: []

我不知道做我想做的事情的最佳方式是什么。如果您找不到解决方案,我也很感谢您提供一些关于替代方法的建议,以便从标准输入中获取每个用户+密码的答案。

这是从标准输入读取的函数:

public static List<Integer> leerRespuesta(List<String> nombrePreguntas) {
    List<Integer> respuestas = new ArrayList<Integer>();
    Scanner in = new Scanner(System.in);
    // Para cada pregunta, habrá una respuesta
    boolean licencia = true;
    for (String np : nombrePreguntas) {
        // just a feature that I must implement
        if(licencia == false && (np.equals("LM2") || np.equals("LM3") || np.equals("LM4"))) {
            continue;
        }

        // Print the name/id of the question
        System.out.print(np + ": ");

        if(in.hasNextLine()) {
            String s = in.nextLine();

            while(!StringUtils.isNumeric(s)) {
                System.out.println("It must be a number.");
                System.out.print(np + ": ");
                if(in.hasNextLine())
                    s = in.nextLine();
            }

            if(np.equals("LM1") && s.equals("1"))
                licencia = false;

            respuestas.add(Integer.parseInt(s));
        }
    }
    in.close();
    return respuestas;
}

谢谢。

你不能多次读取标准输入。 Java不支持这个1.

可以 做的是读取一次标准输入并将其全部捕获为 String。然后重复创建并使用来自String.

StringReaderScanner

1 ....因为典型的操作系统不支持它。