簡體   English   中英

如何檢查用戶輸入是否為字符串

[英]How can I check if the user input is a string

我正在嘗試檢查用戶是否輸入了字符串。 如果用戶輸入一個字符串,我的程序應該輸出一個錯誤信息。 如果用戶輸入一個整數,我的程序應該繼續執行該程序

到目前為止,這是我的代碼,我需要添加另一個條件來檢查用戶是否輸入字符串,我嘗試了一些方法但它們不起作用

public int UserInput() {
    boolean Continueasking = true;
    int Input = 0;
    while (Continueasking) {
        Input = io.nextInt();
        if (Input == 1 || Input==2 || Input==3) {
            Continueasking = !Continueasking;
        } else {
            System.out.println("try again");
        }
    }
    return Input;

nextInt()將用戶輸入解析為整數。 如果用戶輸入無法解析為整數,則會拋出InputMismatchException 您可以捕獲此異常並按照您認為合適的方式處理它。

while (continueAsking) {
    try {
       input = io.nextInt();
    } catch (InputMismatchException ex) {
       // invalid input - handle exception
    }
}

暫無
暫無

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

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