簡體   English   中英

Java Char空字符檢測

[英]Java Char Empty Character Detection

沒錯,即時通訊在eclipse上使用java並不斷出現問題。 我要解決的問題是何時提升用戶按任意鍵。 當輸入鍵並且沒有Char時,程序由於找不到字符而崩潰。

我的代碼是:

Scanner scan = new Scanner(System.in);
    Game game = new Game();
    char quit=' ';

    while (quit != 'N') 
    {
        game.play();

        System.out.println("Play again? Press any key to continue, or 'N' to quit");
        quit = scan.nextLine().toUpperCase().charAt(0);

    }

按下Enter鍵后,由於沒有輸入任何字符,因此停止了程序。 有沒有辦法解決這個問題,並在按Enter鍵時讓程序繼續?

我會這樣寫:

    Scanner scan = new Scanner(System.in);
    String line;

    do{
        game.play();
        System.out.println("Play again? Press any key to continue, or 'N' to quit");
        line = scan.nextLine();

    }while (line.isEmpty() || line.toUpperCase().charAt(0) != 'N');

您可以檢查長度:

while (quit != 'N') 
{
    game.play();

    System.out.println("Play again? Press any key to continue, or 'N' to quit");
    String test = scan.nextLine().toUpperCase();
    if(test != null && test.length() > 0)
    {
       quit = test.toUpperCase().charAt(0);
    }
    else
    {
         //handle your else here
         quit = ' '; //this will keep it from terminating
    }
}

將下一行存儲在字符串中,然后檢查以確保其不為null且其長度至少為1。如果是,則獲取第一個字符。 如果沒有,請決定如何處理這種情況。

而不是quit = scan.nextLine().toUpperCase().charAt(0); ,我們可以這樣寫:

String str = scan.nextLine().toUpperCase();
quit = ((str == null || "".equals(str)) ? ' ' : str.charAt(0));

暫無
暫無

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

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