我試圖驗證用戶只輸入一個整數。是否有另一種方法可以使驗證更加簡化?
Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of subjects that you need to get an average of: ");
int amount_of_subjects;
while (!in.hasNextInt())
{
// warning statement
System.out.println("Please Enter integer!");
in.nextLine();
}
amount_of_subjects = Integer.parseInt(in.nextLine());
uj5u.com熱心網友回復:
看來您的解決方案已經很簡單了。這是一個更簡約的版本:
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
來自https://stackoverflow.com/a/23839837/2746170
盡管您只會減少代碼行數,同時還可能降低可讀性。
uj5u.com熱心網友回復:
取決于你想用你的程式做什么。
如果您只想將有效的整數作為輸入,您可以使用該nextInt()函式
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
如果您想檢查用戶是否輸入了有效的整數來回應,您可以執行以下操作:
public boolean isNumber(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
uj5u.com熱心網友回復:
這是一種更簡單的方法,它驗證整數值 0 - 包括最大值并檢查用戶輸入并最終顯示結果或錯誤訊息。它一遍又一遍地回圈,直到收到好的資料。
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int userVal = 0;
while(true){
try{
System.out.print("Enter a number: ");
userVal = scan.nextInt();
if ((userVal >= 0 && userVal <= Integer.MAX_VALUE)){
System.out.println(userVal);
break;
}
}
catch(InputMismatchException ex){
System.out.print("Invalid or out of range value ");
String s = scan.next();
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425409.html
