亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Java中將輸入作為字符串并限制用戶不輸入整數

在Java中將輸入作為字符串并限制用戶不輸入整數

慕村9548890 2021-11-24 16:14:06
我想在 Java 中將輸入作為字符串并使用 try catch 限制用戶不輸入整數。import java.util.*;public class trycatch {     public static void main(String args[]) {         Scanner sc=new Scanner(System.in);        String a;         System.out.println("\n\nEnter the name");         try {             a=sc.nextLine();             System.out.println("You name is "+a);         }         catch(InputMismatchException b) {             System.out.println("There is problem with your input");         }     } }
查看完整描述

3 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

測試是否是int一個異常,如果不是則拋出異常


a=sc.nextLine(); 

Integer.valueOf(a); // throws NumberFormatException


// this is number so go to top of loop

continue;

} catch(NumberFormatException b) { 

        System.out.println("There is NO problem with your input");

        // we can use `a` out side the loop 


查看完整回答
反對 回復 2021-11-24
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

使用該技術嘗試解析用戶作為 int 輸入的內容。如果轉換成功,這意味著他們輸入了一個整數,你應該拋出一個異常,因為你說你不希望他們輸入一個整數(我理解這意味著你不希望他們只輸入一個數字序列)

我沒有給你確切的答案/為你編寫代碼,因為你顯然在學習 Java,這是一個學術練習。你的大學/學校對教授/評估我的編程能力不感興趣,他們對你的感興趣,所以我為你做你的工作對你沒有任何價值:)

如果您在實施我的建議時遇到困難,請編輯您的問題以包含您改進的代碼,我們可以再次提供幫助

作為旁注,我建議您將錯誤消息做得更好,以“出現問題”對用戶來說,沒有什么比被告知存在問題但不知道問題是什么或如何解決更令人沮喪的了。


查看完整回答
反對 回復 2021-11-24
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

使用正則表達式可以最好地解決此問題,但由于您的要求是使用 try catch,因此您可以使用以下方法


public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String a = null;


    System.out.println("\n\nEnter the name");


    try {

        // try to get Integer if it is number print invalid input(because we

        // don't want number)

        sc.nextInt();

        System.out.println("There is problem with your input");

    }

    //getting exception means input was not an integer

    // if input was not an Integer then try to read that as string and print

    // the name

    catch (InputMismatchException b) {

        a = sc.next();

        System.out.println("You name is " + a);

    }

}


查看完整回答
反對 回復 2021-11-24
  • 3 回答
  • 0 關注
  • 249 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號