首頁  >  文章  >  我不知道如何解決 nextLine 問題並使其正常工作

我不知道如何解決 nextLine 問題並使其正常工作

WBOY
WBOY轉載
2024-02-09 11:54:301115瀏覽

在開發過程中,我們常常會遇到各種問題,有時即使是看似簡單的問題也會讓我們束手無策。例如,你可能會遇到一個讓你困擾的問題,就是如何解決 nextLine 問題並使其正常運作。別擔心,php小編新一在這裡提供大家一些解決這個問題的方法和技巧,希望能幫助大家解決這個難題。下面我們就一起來看看吧!

問題內容

do {
        System.out.println("write in format \"firstname lastname\"");
            
        //just want to scan a sentence with spaces
        String[] tempArr = sc.nextLine().split(" ");
            
        System.out.println("Hello " + tempArr[0]);

        System.out.println("Do you want to do it again Y/N");

    }while(sc.next().equals("Y"));

我不知道如何防止下一行掃描器在第一次迭代後掃描空白

我希望循環運行,直到輸入“y”以外的任何內容

解決方法

我不會為此使用 do...while 循環。您可以透過建立一個無限循環來輕鬆地做到這一點,如果答案不是“y”,該循環就會停止。我假設您想循環使用者輸入 y 並停止其他任何內容。如果相反,只需翻轉 if 語句中的布林值即可。嘗試這樣的事情:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("write in format \"firstname lastname\"");
            String[] tempArr = sc.nextLine().split(" ");
            System.out.println("Hello " + tempArr[0]);
            System.out.println("Do you want to do it again Y/N");
            String answer = sc.nextLine();
            if (!answer.equalsIgnoreCase("Y")) {
                break;
            }
        }
    }
}

以上是我不知道如何解決 nextLine 問題並使其正常工作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除