Every time I run this program I keep coming up upon an infinite loop that keeps repeating the else statement "this password is incorrect" every time I run this program
also what other mistakes did I make here if there is any?
public static void ValidChecker() {
Scanner scanner = new Scanner(System.in);
boolean correct = false;
while(correct == false)
System.out.println("please enter a password");
String pass = scanner.next();
for(int i = 0; i<pass.length(); i++) {
if(pass.charAt(i) == '!' && pass.length() > 8 ) {
System.out.println("this password is correct");
correct = true;
break;
}
else {
System.out.println("this password is incorrect");
break;
}
}
Here's a MRE of your code that fixed that you can run and try yourself. Please make sure you understand where you went wrong so you wont make this mistake again :)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean correct = false;
while(correct == false) {
System.out.println("please enter a password");
String pass = scanner.next();
for(int i = 0; i<pass.length(); i++) {
if(pass.charAt(i) == '!' && pass.length() > 8 ) {
System.out.println("this password is correct");
correct = true;
break;
}
else {
System.out.println("this password is incorrect");
break;
}
}
}
}
}
The mistake in your code was the missing curly braces (The {
at the start and }
at the end of your loop). Remember, conditions like if
, while
etc. will only run the first line after the condition if there are no curly braces. Which in your case it would run while(correct == false) System.out.println("please enter a password");
, where correct
never becomes false. So it ends up looping infinitely printing "please enter a password".