在使用Gradle构建的Java控制台应用程序中使用system.in的替代方法?

时间:2018-09-20 12:44:38

标签: java gradle

我有一个基本的控制台应用程序,我只是试图在while循环中使用一个简单的Scanner来捕获用户输入。我尝试将standardInput = System.in放在build.gradle中,但是我的程序在等待输入时不会阻塞。

while (stillWriting) {
        System.out.println(
                        "Press 1 to write something,\n" +
                        "Press 2 to erase something,\n" +
                        "Press 3 to exit."
        );
        //if you select 1, it goes into the case, but does not block
        //then ends up here again.
        int userSelection = scanner.nextInt();
        switch (userSelection) {
            case 1:
                System.out.println("Enter text to be written: ");
                 //vvvvvv should block here but doesn't. vvvvvv
                String textToWrite = scanner.nextLine();
                paper = pencil.write(paper, textToWrite);
                break;
            case 2:
                //some code
                break;
            case 3:
                stillWriting = false;
                break;
            default:
                System.out.println(userSelection + " is not valid.");
                break;
        }
    }

我是否可以使用其他替代方法或jar使其正确阻塞并实际上等待输入?

2 个答案:

答案 0 :(得分:0)

在每种情况下都想输入,如果您只是将新的Scanner()重新分配给扫描器变量,它将正确阻止。

尽管如此,仍然不会选择换行符。

答案 1 :(得分:0)

您必须消耗用户输入的<Enter>才能做出选择,否则String textToWrite = scanner.nextLine();会(立即)消耗它:

[...]

int userSelection = scanner.nextInt();
scanner.nextLine();   // <-- consume the <enter>

switch (userSelection) {

[...]