Reputation: 31
I have a little issue with my Java program. I'm supposed to prompt the user for a distinct password pattern. I need the format DDLLDD (D=digit, L=letter) but I'm not quite sure how to approach this.
I've tread searching for questions similar but I've only found the ones where you're supposed to check if the input has a digit/letter in any order. I found some regex stuff too but I've never used those before, I've only gone with while/for loops to check for character input.
I've given it a try but I don't think I'm getting it. I tried checking each character index.
Scanner s = new Scanner(System.in);
String input = null;
// Prompt
System.out.print("Enter input: ");
input = s.nextLine();
// Check length
while(!(input.length()==6))
{
System.out.print("Re-Enter input: ");
input = s.nextLine();
}
boolean inputcheck = false;
while(inputcheck)
{
char ch = input.charAt(0);
char ch1 = input.charAt(1);
char ch2 = input.charAt(2);
char ch3 = input.charAt(3);
char ch4 = input.charAt(4);
char ch5 = input.charAt(5);
boolean check = Character.isDigit(ch);
boolean check1 = Character.isDigit(ch1);
boolean check2 = Character.isLetter(ch2);
boolean check3 = Character.isLetter(ch3);
boolean check4 = Character.isDigit(ch4);
boolean check5 = Character.isDigit(ch5);
if((check==true)&&(check1==true)&&(check2==true)&&(check3==true)&&(check4==true)&&(check5==true));
{
inputcheck = true;
}
}
System.out.println("PASS");
Upvotes: 0
Views: 200
Reputation: 16067
I'm not a pro with regex but this might suits your need :
\\d{2}\\D{2}\\d{2}
Basically it means :
\d //Any digit, short for [0-9]
{2} //Occurs 2 number of times,
\D //non-digit, short for [^0-9]
do{
System.out.print("Input: ");
input = s.nextLine();
} while (!input.matches("\\d{2}\\D{2}\\d{2}"));
You can learn more about regex here.
Upvotes: 3
Reputation: 1511
Check your logic carefully. Your code as shown appears to only "pass" passwords that are ALL digits. Specifically, check2
and check3
probably need to be the opposite of what they are, either by:
boolean check2 = !Character.isDigit(ch2);
or
...&&(check2==false)&&...
Upvotes: 0