[英]Input validation with 3 validation parameters in java
我有這段代碼來驗證輸入,這個輸入與用戶的賭注有關
我現在擁有的代碼如下:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf(input + " is not a valid number.\n");
}
number = scanner.nextInt();
} while (number < 0);
System.out.printf("You have entered the number " + number);
我有 1. 和 2. 用這段代碼弄清楚,但我不能無緣無故地添加第三 (3.) 語句,因為它要求雙倍相同的輸入,或者它給出錯誤 InputMismatchException 因為它假設是integer,但在測試中有時會這樣做。
這個數字應該是賭注
請幫忙xD
您的邏輯相當復雜,難以理解。 我認為在完成這項任務之后,您應該尋求一些幫助並找到一種更好的方法來構建此代碼。 (目前,講師通常會要求您上交自己的作業,因此我不會嘗試更改您的代碼。)
您現在擁有代碼的方式必須分兩部分進行最后檢查。 首先,檢查然后決定是否打印錯誤信息。 其次,檢查並決定是否繼續循環。
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf(input + " is not a valid number.\n");
}
number = scanner.nextInt();
if( number > credits )
System.out.println( "Not enough credits." );
} while (number < 0 || number > credits);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.