簡體   English   中英

用戶輸入字符而不是int時出錯(Java)

[英]Error when user enters a char instead of an int (Java)

我有一個非常簡單的問題(我正在啟動Java),但是由於某種原因,我找不到合適的答案。 我正在編寫程序,用戶必須做出選擇和輸入。 但是我需要對有效輸入進行一些檢查,如果他輸入的是char而不是int ,我需要給他一個錯誤消息。

代碼是:

Scanner n = new Scanner (System.in);
System.out.print("...");
    sp = n.nextInt();
    if ( sp != 1 )
    {
        if ( sp == 2 )
        {
            System.out.println("...");

        }
    }
    else 
        System.out.println("...");

    **//and here the error message shoub be,** 
    **//in case the user inputs something different than a int**

您是否嘗試過使用Java的try .... catch語句。 我建議您像這樣包裝代碼:

try{
       //put your code here
} catch(e){
       System.out.println(e.message)
}

您可以研究有關處理IO錯誤的更多信息,並在代碼中增加一些保護。 希望這可以幫助!

您可能需要像這樣添加try catch ...應該可以正常工作...如果用戶現在輸入字符串,它將拋出異常,並且catch塊將起作用

Scanner n = new Scanner (System.in);
System.out.print("..."); 
try{
    sp = n.nextInt();
} catch(Exception e){
       //Display your message here
}
if ( sp != 1 ) { 
    if ( sp == 2 ) { 
        System.out.println("...");
    } 
} else 
       System.out.println("..."); 

暫無
暫無

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

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