Issues with proper looping in a do while loop - Java - java

I seem to be having some issues with my program. I was advised to use a do while loop by my instructor to keep the program running. However, it errors out when I type in an invalid password and restarts. When I input a valid password it only prints "Valid Password" and does not loop. Where have I gone wrong?
import java.util.Scanner;
public class CovenduniteProg5_FIX {
public static void main(String[] args) {
boolean passwordValid = false;
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n" +
"\tIs at least 8 characters long\n" +
"\tContains at least 1 lower letter character\n" +
"\tContains at least 1 upper letter character\n" +
"\tContains at least 1 numberic digit\n" +
"\tContains at least 1 special character from the set: !##$%^&*\n" +
"\tDoes not contain the word \"and\" or the word \"the\"\n");
System.out.print("Enter your password: ");
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&' || ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8 ) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if(!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit && !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
} while (!passwordValid);
passwordValid = false;
while(!passwordValid) {
if (passwordValid)
System.out.print("\nPassword is valid.");
}
}
}

We don't need the second while loop, it's basically an infinite loop. Also, we need to move the "Password Verifier" statements outside the while loop as they needn't be printed multiple times. So, the method will look something like this:
public static void main(String[] args) {
boolean passwordValid = false;
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n" + "\tIs at least 8 characters long\n"
+ "\tContains at least 1 lower letter character\n" + "\tContains at least 1 upper letter character\n"
+ "\tContains at least 1 numberic digit\n"
+ "\tContains at least 1 special character from the set: !##$%^&*\n"
+ "\tDoes not contain the word \"and\" or the word \"the\"\n");
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your password: ");
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&'
|| ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if (!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit
&& !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
} while (!passwordValid);
}

You put the last passwordValid = false; outside the do-while when you should just have it once before the loop. And you also do not need the second while(!passwordValid) loop:
boolean passwordValid = false; //← only here
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
Scanner stdIn = new Scanner(System.in);
/*
...
*/
if (/*All sub-conditions met*/)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
}
while (!passwordValid);
//passwordValid = false; ← remove this
//no need for while or if statment, because you can only reach this code if passwordValid = true
System.out.print("\nPassword is valid.");

The following code will do what you ask. Some things to consider :
The second while loop is infinite.
Declare the scanner outside the do loops...creating one everytime could cause issues and you only need to declare and create it once.
Use two do loops, the outer loop has an infinite condition so it will continue forever...you can re-write to terminate in some fashion.
the outer loop displays your menu.
the inner loop does all you scanner/input and validation and determination.
Hope this helps
// CovenduniteProg5_FIX
public static void main(String[] args) {
boolean passwordValid = false;
Scanner stdIn = new Scanner(System.in);
do {
System.out.println("Password Verifier");
System.out.println("\nEnter a password that meets the following rules:\n"
+ "\tIs at least 8 characters long\n" + "\tContains at least 1 lower letter character\n"
+ "\tContains at least 1 upper letter character\n" + "\tContains at least 1 numberic digit\n"
+ "\tContains at least 1 special character from the set: !##$%^&*\n"
+ "\tDoes not contain the word \"and\" or the word \"the\"\n");
System.out.print("Enter your password: ");
do {
boolean invalidLength = false;
boolean containsRestrictedWord = false;
boolean containsLowerCaseLetter = false;
boolean containsUpperCaseLetter = false;
boolean containsDigit = false;
boolean containsSpecialChar = false;
try {
String password = stdIn.nextLine();
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) && !containsUpperCaseLetter) {
containsUpperCaseLetter = true;
}
if (Character.isLowerCase(ch) && !containsLowerCaseLetter) {
containsLowerCaseLetter = true;
}
if (Character.isDigit(ch) && !containsDigit) {
containsDigit = true;
}
if ((ch == '!' || ch == '#' || ch == '#' || ch == '$' || ch == '%' || ch == '^' || ch == '&'
|| ch == '*') && !containsSpecialChar) {
containsSpecialChar = true;
}
}
if (password.length() < 8) {
invalidLength = true;
}
if (password.contains("and") || password.contains("the")) {
containsRestrictedWord = true;
}
if (invalidLength) {
System.out.println("Invalid: Invalid length");
}
if (containsRestrictedWord) {
System.out.println("Invalid: Contains either the word \"and\" or \"the\".");
}
if (!containsDigit) {
System.out.println("Invalid: Does not contain at least one digit.");
}
if (!containsLowerCaseLetter) {
System.out.println("Invalid: Does not contain at least one lowercase letter.");
}
if (!containsUpperCaseLetter) {
System.out.println("Invalid: Does not contain at least one uppercase letter.");
}
if (!containsSpecialChar) {
System.out.println("Invalid: Does not contain at least one special character.");
}
if (containsSpecialChar && containsUpperCaseLetter && containsLowerCaseLetter && containsDigit
&& !containsRestrictedWord && !invalidLength)
passwordValid = true;
if (passwordValid)
System.out.print("\nPassword is valid.");
}
catch ( Exception ltheXcp ) {
ltheXcp.printStackTrace();
}
} while (!passwordValid);
passwordValid = false;
} while ( 1 != 2 );
// while (!passwordValid) {
// if (passwordValid)
// System.out.print("\nPassword is valid.");
// }
}

Related

Is there a char.length command?

// I am stuck trying to get my program to only accept a single character from the scanner. Right now the program will accept any amount of characters as long as the first letter is one of the listed letters. I would like to rewrite this code with out the charAt(0) if possible or to add a if statement. if(sea.length > 1){} something like that. I hope I explained the issue well enough to understand. Any help is appreciated, and thank you for your time.
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
return sel;
}
Is there a char.length command?
No, there is no such command. You need to get the input using Scanner::nextLine() and check the length of the input String.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
Scanner in = new Scanner(System.in);
System.out.println(promptForChoice(in));
}
public static char promptForChoice(Scanner in) {
char sel = 0;
String input;
boolean valid;
do {
valid = true;
System.out.print("Enter H/L/S [High/Low/Seven]: ");
try {
input = in.nextLine();
sel = input.toUpperCase().charAt(0);
if (input.length() == 1 && (sel == 'H' || sel == 'L' || sel == 'S')) {
return sel;
} else {
throw new IllegalArgumentException("You must enter only H, L or S.");
}
} catch (IllegalArgumentException e) {
valid = false;
System.out.println(e.getMessage());
}
} while (!valid);
return sel;
}
}
A sample run:
Enter H/L/S [High/Low/Seven]: hello
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: High
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: M
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: H
H
Feel free to comment in case of any doubt/issue.
You could get the input from the scanner and put it into a string, then u can do string.length and check it!
the Character length is always 1, I suppose you could achieve what you need with
public static char promptForChoice(Scanner in) {
if(in.next() == "H" || in.next() == "L" || in.next() == "S") {
System.out.println("High, Low or Seven(H/L/S");
return (char) in.next();
}
else {
System.out.println("You must enter only H, L or S.");
// you must always have a return value, in this case
//e.g. the automatically initialized char value
return '\0';
}
}
with your code you could do something like
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
if(in.next().length == 1) {
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
}
else System.out.println("You must enter only one single character");
return sel;
}

Do while loop for Try again program not working correctly (java)

I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting

Why are these errors coming?

I am trying to make a fraction calculator that quits when you type quit regardless of the casing. However these two errors have been coming up. Any suggestion?? Thanks a lot.
FractionCalculator.java:70: error: '(' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: ')' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: 'else' without 'if'
else if kb.next().equalsIgnoreCase("quit"){
^
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner (System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " +userName +", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner (System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: " +input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
}
else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*' || input.charAt(i) == '/' && operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i=i+1;
}
if (input.charAt(i) != ' ' && value1Done == true && value2Done == false) {
value2Str += input.charAt(i);
}
else {
value2Done = false;
}
else if kb.next().equalsIgnoreCase("quit"){
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
//correctFormat = true;
}
}
System.out.println("value1Str is: " +value1Str);
System.out.println("Operator is: " +operator);
System.out.println("Value2Str is: " +value2Str);
}
}
You have errors in using if condition .
Updating your code with proper use of if , if else conditions.
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner(System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " + userName
+ ", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner(System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: "
+ input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
} else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-'
|| input.charAt(i) == '*' || input.charAt(i) == '/'
&& operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i = i + 1;
}
if (input.charAt(i) != ' ' && value1Done == true
&& value2Done == false) {
value2Str += input.charAt(i);
} else if (kb.next().equalsIgnoreCase("quit")) {
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
// correctFormat = true;
} else {
value2Done = false;
}
}
System.out.println("value1Str is: " + value1Str);
System.out.println("Operator is: " + operator);
System.out.println("Value2Str is: " + value2Str);
}
}
Check how to use if-then and if-then-else Statements at this link :
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You have a malformed if statement:
if (...) { ....
}
else {
value2Done = false;
}
else // ERROR
An if statement cannot have two else clauses ... which you have here.
Indeed, the 3rd error message is saying that explicitly.

Java phrase guessing game

Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.

Is there a more efficient way to check characters in a string?

For this assignment, I need to accept a lock combination and check if:
It is 9 chars long
At position 2,8 the char is R or r
At position 5 the char is l or L
All of the other positions are integers 0-9
I am wondering if there is a better way to do this than checking each position for a digit?
Scanner input = new Scanner(System.in);
String lockComb;
System.out.print("Please enter a lock combination ( ddRddLddR ): ");
lockComb = input.nextLine();
if((lockComb.length() == 9) && ((lockComb.charAt(2) == 'r') || (lockComb.charAt(2) == 'R')) &&
((lockComb.charAt(5) == 'l') || (lockComb.charAt(5) == 'L')) && ((lockComb.charAt(8) == 'r')
|| (lockComb.charAt(8) == 'R')))
{
if((Character.isDigit(lockComb.charAt(0))) && (Character.isDigit(lockComb.charAt(1))) &&
(Character.isDigit(lockComb.charAt(3)) && (Character.isDigit(lockComb.charAt(4))) &&
(Character.isDigit(lockComb.charAt(6))) && (Character.isDigit(lockComb.charAt(7)))))
{
System.out.println(lockComb + " is a valid lock combination!");
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
To simplify things, you can use a regular expression:
if (lockComb.matches("[0-9][0-9][rR][0-9][0-9][lL][0-9][0-9][rR]")
(That's lowercase-l and uppercase-L in the middle.)
(No need to check the length, which is implicitly defined by the regular expression.)
How about just for fun a solution that doesn't involve regular expressions. I'm not arguing at all for or against just merely a different solution. One thing you do lose if using a regular expression is the ability to tell exactly why this is not a valid lock combination. It's up to you to figure out what the best solution is given the scenario you are coding for.
public static boolean matcher (String lockComb) {
if(lockComb.length() != 9) {
System.out.println(lockComb + " is not a valid lock combination!");
return false;
}
boolean isValid = true;
char[] comb = lockComb.toUpperCase().toCharArray();
for (int i = 0; i < comb.length; i++) {
switch (i) {
case 2:
case 8:
isValid = (comb[i] == 'R');
break;
case 5:
isValid = (comb[i] == 'L');
break;
default:
isValid = Character.isDigit(comb[i]);
break;
}
if(isValid == false) break;
}
if(isValid) {
System.out.println(lockComb + " is a valid lock combination!");
} else {
System.out.println(lockComb + " is not a valid lock combination!");
}
return isValid;
}

Categories

Resources