'Nested if statement is only executing first part
What I want my code to do
I want my code to validate user input without using Regex or isDigit operators. If all the requirements of the if statements are found then I want the code to print out that it is valid. If any of them are not found I want it to print they are not valid.
regPlate is a string which I get from user input.
What I've tried
I've tried using nested if statements to certain parts of the string of user input.
The problem
My code compiles ok, but when I run it only the first if statement is used for validation. It is not going further down the if block statement. It only validates whether the user inputs values for the first 3 chars of the string. It also never prints out whether the string entered is valid. Only if it is invalid, having not entered the first 3 chars correctly.
My code
//String to hold numbers
String year = "0123456789";
String letters = "abcdefghijklmnopqrstuvwxyz";
char hyphen = '-';
String sub = regPlate.substring(4,5);
String sub2 = regPlate.substring(7);
//if year does not have the character at regPlates index declare it as invalid
if(year.indexOf(regPlate.charAt(0)) != -1 && year.indexOf(regPlate.charAt(1)) != -1 &&
year.indexOf(regPlate.charAt(2)) != -1){
if(regPlate.charAt(3) == hyphen){
if(sub.length() == 2){
if(regPlate.charAt(6) == hyphen){
if(sub2.length() >= 4 || sub2.length() <= 6){
System.out.println("valid");
}
}
}
}
}
else{ System.out.println("invalid");
}
Any advice would be great, thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|