0

I am a Java beginner.

This is the output I got after testing this class:

Enter username: abc
Enter password: 123
Enter your name and we will call you that: abc123
Enter your position (Manager or Engineer): Manager
Enter your position (Manager or Engineer): Engineer
Enter your position (Manager or Engineer): Manager
Enter your position (Manager or Engineer): Engineer

This loop goes on forever. I think what happens here is the while loop checks the instance variable before the changing of the value and keep checking it or it's something else.

import java.util.*;
public class Employee
{
    Scanner inputUsername = new Scanner(System.in);
    Scanner inputPassword = new Scanner(System.in);
    Scanner inputName = new Scanner(System.in);
    Scanner inputPosition = new Scanner(System.in);
    
    private String name;
    private String position;
    protected String username;
    protected String password;
    
    public void signup()
    {
        System.out.print("Enter username: ");
        username = inputUsername.nextLine();
        System.out.print("Enter password: ");
        password = inputPassword.nextLine();
        System.out.print("Enter your name and we will call you that: ");
        name = inputName.nextLine();
        
        do
        {
            System.out.print("Enter your position (Manager or Engineer): ");
            position = inputPosition.nextLine();
        }while(position != "Manager" || position != "Engineer");
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
EislynGwyneth
  • 57
  • 1
  • 7
  • 2
    Also, there's no reason to create all those `Scanner` objects. You can use just one. – 001 Aug 11 '21 at 15:17
  • 1
    I can just use one scanner object for one input data type? – EislynGwyneth Aug 11 '21 at 15:18
  • 3
    You can call `nextLine()` repeatedly on the same `Scanner`. Things get a bit tricky when reading strings and numbers: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045) – 001 Aug 11 '21 at 15:19
  • 1
    @Ryan Tan You can use the same `Scanner` for anything that the `Scanner` was opened on. All of your `Scanner`s are opened using `System.in` so they are all equivalent to each other and redundant. You only would need a 2nd `Scanner` if you wanted to then open one on a `File`. – Nexevis Aug 11 '21 at 15:19

0 Answers0