![](/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.