如何限制用户在java中输入4位pin



我想从用户那里获得引脚的输入,我想限制用户使用4位引脚。我尝试过[但当我输入0001时,它不起作用,再次要求输入4位密码,然后请解决

void pin1()
{
//int pin;
for(int i=1;i<=1000;i++)
{
try
{
pin=obj.nextInt();
if(pin<=9999 && pin>=1000)
{
}
else
{
System.out.println("Pin must be four digit");
pin1();
}
break;
}
catch(InputMismatchException e)
{
obj.next();
System.out.println("Error use numbers not alphabets or characters");
}
}
}

您为引脚选择了错误的类型。作为int的值,00011是相同的值,但后者是无效引脚,而前者是有效引脚。

您应该使用String来存储引脚。这意味着您应该调用nextLine而不是nextInt:

String pin = obj.nextLine();

要检查此pin是否包含4位数字,我们可以使用正则表达式d{4}

Matcher m = Pattern.compile("\d{4}").matcher(pin);
if (m.matches()) {
System.out.println("You have entered a 4-digit pin");
} else {
System.out.println("You have not entered a 4-digit pin");
}

或者,您可以使用for循环进行检查:

if (pin.length() != 4) {
System.out.println("You have not entered a 4-digit pin");
} else {
boolean allDigits = true;
for (int i = 0 ; i < 4 ; i++) {
if (!Character.isDigit(pin.charAt(i))) {
allDigits = false;
break;
}
}
if (allDigits) {
// pin is valid
} else {
System.out.println("Error use numbers not alphabets or characters"); 
}
}

试试这个

do { 
System.out.print("Please enter a 4 digit pin:"); 
input = reader.nextLine(); 
if(input.length()==4){
//allow
}
}while( input.length()!=4);

代码的问题是

`if(pin<=9999 && pin>=1000)` 

允许1000和9999之间的数字,但0001或0300仍然是有效的4位数字

该代码只允许numeric,不允许alpha numeric导入java.util.Scanner;

public class Post7 {
public static void main(String[] args) {
String regex = "\d+";
Scanner sc = new Scanner(System.in);
System.out.println("please input a valid 4 digit pin");
while(true) {
String ln = sc.nextLine();
if(ln.length() == 4 && ln.matches(regex)) {
System.out.println("valid input "+ln);
break;
}else {
System.out.println("please input a valid 4 digit pin");
}
}
sc.close();
}
}

您正在将0001读取为不满足条件pin>=1000的整数1。您可以做的一件事是首先检查字符串的长度,如果不是4,则返回一个错误。然后,如果尝试转换为整数是正确的:如果出现错误,可能用户没有插入4位数字。

试试这个。

public static void main(String[] args) {

Scanner s = new Scanner (System.in);

int pin;
int attempt = 0;

while(attempt < 3) {

System.out.print("Enter PIN: ");
pin = s.nextInt();
System.out.println("");
s.nextLine(); //spacing for 2nd and 3rd attempts

if(pin >= 1000 && pin <= 9999) break;
else System.out.println("Please try again."); 
System.out.println("");
attempt ++;
}

if(attempt < 3) System.out.println("You have successfully logged in!");
else System.out.println("Your card has been locked.");

}

最新更新