請解釋一下,我在做的時候有點迷惑。 如果我第一次輸入城市名稱,一切都正常。但如果我輸入一個數字,我得到一個相應的訊息,當我試圖第二次輸入城市名稱時,它給出了同樣的訊息。(關于無效資料)
String town=scanner.nextLine()。
boolean tryagain = false。
do {
if (town.charAt(0) >= '0' && town. charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format")。
scanner.nextLine();
tryagain = true; }
else {
tryagain = false;
}
}while(tryagain)。
我還嘗試了try和catch選項,但是如果用戶輸入的是數字而不是字串,我就無法寫出例外。它不起作用。請幫助我。
try {
System.out.println("輸入城市的名稱")。
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format");
scanner.nextLine()。
}
uj5u.com熱心網友回復:
注意這行代碼的不同之處:
town = scanner.nextLine();
以及這行代碼:
scanner.nextLine()。
它們都接受來自控制臺的輸入,但其中只有一個將輸入存盤在town變數中。 要用新輸入的值來更新town變數,請將該值存盤在該變數中:
town = scanner.nextLine();
uj5u.com熱心網友回復:
試試這個。在if塊中,將scanner.nextLine()保存為town變數,以便在下一次迭代中檢查它是否只由數字組成或為空。
scanner scanner = new Scanner(System. in)。)
String town=scanner.nextLine();
boolean tryagain;
do {
if (town.matches("[0-9]*"/span>)){
System.out.println("You probably entered an invalid data format")。
town = scanner.nextLine();
tryagain = true; }
else {
tryagain = false;
}
} while (tryagain);
uj5u.com熱心網友回復:
把它放在try塊中,并嘗試將其決議為Integer
。 try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331106.html
標籤:
上一篇:2段的交叉點
