![](/img/trans.png)
[英]In the java programming, if the input validation fails, how can I allow user to retry three times before throwing an exception and terminating?
[英]How to properly use this while loop within my method to have user retry input to a maximum of three times
嗨,我正在創建一個模擬 atm,我創建了一種方法來檢查用戶的 pin 輸入是否錯誤,但是如果輸入錯誤,它會向不正確的 pin 發送 3 次垃圾郵件然后我的程序停止,我正在研究如何讓用戶輸入錯誤讓它告訴他們一次錯誤,然后讓他們重試他們的 pin,直到他們達到最大 3 次嘗試。
我的 while 循環是在我的 ATM 課上(第一次和我一起裸露)
主要的
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner enterPin = new Scanner(System.in);
System.out.println("Enter your 4 digit pin: ");
String userPin = enterPin.nextLine();
ATM pin = new ATM("1234");
pin.checkPin(userPin);
}
}
提款機類
public class ATM {
String pin;
int counter;
public ATM(String pin){ //constructor 1 for pin
this.pin = pin;
}
public ATM(int counter){ //constructor for counting how many times pin is entered
this.counter = counter;
}
public String getPin(){
return pin;
}
public boolean setPin(String pin){
this.pin = pin;
return true;
}
public boolean checkPin(String userPin){
while(!userPin.contains(pin) && counter < 3) {
System.out.println("Incorrect pin.");
counter += 1;
if (counter >= 3){
System.out.println("Incorrect pin your account has been blocked.");
return false;
}
}
if(userPin.contains(pin)){
System.out.println("Your pin is correct!");
}
return true;
}
}
我在您的代碼中沒有看到任何用戶輸入(即沒有掃描儀接收用戶輸入),所以發生的事情是 userPin 在每個循環中保持不變。
[userPin is false --> count++ --> print "Incorrect pin"] 重復 3 次,這就是垃圾郵件 3 次的原因。
這是我重寫的代碼:
public boolean checkPin() {
int counter = 0;
Scanner scanner = new Scanner(System.in);
while(counter < 3) {
String userPin = scanner.nextLine();
if(userPin.contains(pin)){
System.out.println("Your pin is correct!");
return true;
}
System.out.println("Incorrect pin.");
counter += 1;
}
System.out.println("Too many tries, your account has been blocked.");
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.