This is probably a really simple mistake, but I'm a beginner with Java (and programming in general) and I was curious why the break statement won't work in my program.
public class ValidateStudentNumber
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do{
System.out.println("Enter a number: ");
String number = kb.next();
boolean valid = true;
for (int i = 0; i < number.length(); i++){
char c = number.charAt(i);
if(! Character.isDigit(c)) {
valid = false;
break;
}
if ( number.length() != 7) {
valid = false;
}
}
if (valid){
System.out.println("Valid");
}
else{
System.out.println("Invalid");
}
}
while (kb.hasNext());
System.out.println ("Program ending due to end-of-file");
}
}
What I want to accomplish with this code is that as soon as a letter is typed, the breaks out of the for statement and displays "Invalid", yet when I run the program and type something that is a non-digit, it doesn't leave the for loop and allows me to continue typing as usual.
Thank you for your time.