Home > Software engineering >  Is it not possible to use while statements with if?
Is it not possible to use while statements with if?

Time:01-27

I'm new to Java, and I'm trying to make a password/pin system that while loops back to scanner if incorrect and says "welcome" if input is correct, but it doesn't work. I don't know how to fix it.

while (pass != newentry) {
                
    if (pass == newentry) {
        System.out.println("welcome");
        break;
    }

    System.out.println("try again");
    type.nextInt();
}

I also tried using the do-while loop

System.out.println("Input pin to access files");
                
int newentry= type.nextInt();

do {
    System.out.println("Wrong. Try again");
    type.nextInt();
} while (newentry != pass );

img1
img2

I expected it to loop back to scanner if pin is incorrect and say welcome if pin is correct.

CodePudding user response:

It's unclear from your code what you've tried. Next time please provide complete example.

To compare strings, use rather .equals() method

Here I've tried to give you small functional example:

public class JustATest {
    private static final String PASSWORD = "Sup3rs3cr3t";

    public static void main(String[] args) {
        try (final Scanner command = new Scanner(System.in)) {
            boolean shouldRetry = true;

            while (shouldRetry) {
                final String enteredPassword = command.nextLine();
                if (PASSWORD.equals(enteredPassword)) {
                    System.out.println("Welcome");
                    shouldRetry = false;
                } else {
                    System.out.println("Your password is wrong");
                }
            }
        }
    }
}

CodePudding user response:

Since while(pass!=newentry) is true to enter the loop if(pass==newentry) must be false (IDE should actually hint you this). Rethink your conditions.

CodePudding user response:

The problem is that the if statement is inside the while loop and you don't make the user write until the end of the loop. Thus it won't be able to go inside the if statement even if the user has given a valid password.

This code should do what you asked for:

import java.io.*;

public class Test {
  public static void main(String [] args) throws Exception{
    BufferedReader newentry = new BufferedReader(new InputStreamReader(System.in));
    //This is the password that the user will input    
    String user = null;
    //Set the password that you want here
    String pass = "test1234";
    System.out.println("Enter the password: ");
    while (!pass.equals(user)) {
      //The user enters the password
      user = newentry.readLine();
      
      if (pass.equals(user)) {
          System.out.println("Welcome!");
          break;
      }
      System.out.println("Try again");
    }
  }
}

The BufferedReader is necessary to be able get the user input.

  • Related