Skip to content
Advertisement

Can’t input anything after the User obj3 = new User(); part

i cannot input anything after the User obj3 part. Can anyone help me on what’s wrong with it? i didn’t know what to do already.

public class test {

    public static void main(String[] args) {
        
        Scanner input = new Scanner (System.in);
        Administrator obj = new Administrator();
        
        
        System.out.print("Enter user ID: ");
        String userID = input.nextLine();
        
        System.out.print("Enter user password: ");
        int userPassword= input.nextInt();
        
        System.out.print("Enter user Phone Number: ");
        long phoneNo = input.nextLong();
        
        Administrator obj1 = new Administrator(userID, userPassword);
        Administrator obj2 = new Administrator(userID, userPassword, phoneNo);
        
        User obj3 = new User();
        
        System.out.println("ID : ");
        String ID = input.nextLine();
        
        System.out.println("Password : ");
        int pass = input.nextInt();
        
        User obj4 = new User(ID,pass);
        
        
        if (userID == ID && userPassword==pass){
            System.out.print("Login succesfully!");
        }
       
    }
    
}

Advertisement

Answer

It looks like a problem with the way you used Scanner. I tried to run this myself (with User and Administrator commented out), and it skipped over the ID: and Password: inputs.

Scanner has a few catches to it. One of them is that nextLong() doesn’t grab all the input from a line, only the first long it finds, separated by whitespace. Which means that the Scanner is still on the previous line when you call nextLine(). It just grabs the remainder of what is on the line when you fetched the phone number.

The easiest way to fix this would be to get rid of all of your nextInt() and nextLong(), and replace them with nextLine(). Once you have done that, use Integer.parseInt() to convert the Strings that are outputted from nextLine() into Integers, or use Long.parseLong() to convert to Longs.

Also, you are comparing String like this.

if (userID == ID && userPassword==pass)

It might be better for you if you did it like this instead.

if (userID.equals(ID) && userPassword==pass)

Remember, .equals() is how you compare Strings (or any type of Object).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement