如果扫描仪读取特定输入,则中断

时间:2015-03-09 21:00:01

标签: java java.util.scanner

我有一个读取输入的扫描程序,但它在读取'q'时需要退出。 问题是我找不到办法做到这一点。

Scanner sc = new Scanner(System.in);
System.out.println("question 1");
str1 = sc.nextLine();
System.out.println("question 2");
str2 = sc.nextLine();
System.out.println("question 3");
str3 = sc.nextLine();

问题代表用户信息...... 这只是一个示例代码,但只要用户按 q 它就必须退出,它就会显示我的问题。有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

通常它会像这样完成

String input = "";
ArrayList<String> list = new ArrayList<String>();
while (!(input = scan.nextLine()).equals("q")) {
    // store the input (example - you can store however you want) 
    list.add(input);
}

但在您的情况下,您还可以合并一系列可循环使用的问题。

ArrayList<String> questions = new ArrayList<String>();
questions.add("q1");
questions.add("q2");
questions.add("q3");

Scanner scan = new Scanner(System.in);

String input = "";
ArrayList<String> userInput = new ArrayList<String>();
int index = 0;

// print the first question and increment the index
System.out.println(questions.get(index));
index++;

while (!(input = scan.nextLine()).equals("q")) {
    // store the input (example - you can store however you want) 
    userInput.add(input);

    // print the next question since the user didn't enter q
    // if there are no questions left, stop asking
    if (index == questions.size() - 1) {
        break;
    }
    System.out.println(questions.get(index));

    // keep track of the index!!
    index++;
}

scan.close();

在问题结束时,您可以使用userInputs列表中的值。答案从索引0开始存储,并对应于匹配的问题列表。

另一方面,如果您确实想要检测用户何时按下&#34; q&#34;在他按下回车之前,你可以在q按钮上实现一个KeyListener ...(但是,这会在每次用aq启动用户的有效输入时停止程序)有关详细信息,请参阅http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html

答案 1 :(得分:0)

在我之前的人是正确的,但你也可以尝试

String input = ""
ArrayList<String> list = new ArrayList<String>();
while (true){
     input = sc.nextLine();
     if (input.equals("q"))
         break;
     list.add(input)
}

更具可读性,您停止代码的意图更加明确。

希望这有帮助。

相关问题