簡體   English   中英

Java-多次使用掃描儀

[英]Java - Using Scanner multiple times

我目前正在嘗試從控制台中的用戶那里獲取輸入,執行一些操作,然后從控制台中獲取更多輸入。

Scanner userInput = new Scanner(System.in);
while(true){
    System.out.print("Enter input: ");
    String foo = userInput.nextLine();
    //do stuff with foo
}

每當執行此操作時,循環的第一次運行都可以正常工作,但是隨后的每次運行都將foo輸出為空,並且不允許我添加更多輸入。

//above code
System.out.println(foo);
//nothing prints

我應該如何使它每次都提示輸入,並確保它不僅使用空白字符串?

你是說喜歡

    Scanner userInput = new Scanner(System.in);
    while(true){
        System.out.print("Enter input: ");
        String foo = userInput.nextLine();

        if (foo.length () == 0) {
            break;
        }

        //do stuff with foo
        System.out.format("[%s]\n",foo);
    }

在Scanner類中沒有readLine方法,您可以像這樣使用它

Scanner userInput = new Scanner(System.in);
while (true) {
            System.out.print("Enter input: ");
            String foo = userInput.nextLine();
            System.out.println(foo);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM