Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UserLogin Program in java I could not find my mistake.Can you plz help me out

When I enter "helloworld" as username the program returns username is incorrect. I could not understand what my problem is.

import java.util.Scanner;

public class Main {
    
    public static void main (String[] args) {
        
        String userName, sys_userName = "helloworld";
        int passWord, sys_passWord = 12345;
        
        Scanner scan = new Scanner (System.in); 
        
        System.out.println("Enter username: ");
        userName = scan.nextLine();
        
        System.out.println("Enter password: ");
        passWord = scan.nextInt();
        
        if ((userName == sys_userName) && (passWord == sys_passWord)) {
            
            System.out.println("Welcome!");
        }
        
        else if ((userName != sys_userName) && (passWord == sys_passWord)) {
            
            System.out.println("Username is incorrect!");
        }
        
        else if ((userName == sys_userName) && (passWord != sys_passWord)) {
            
            System.out.println("Password is incorrect!");
        }
        
        else if ((userName != sys_userName) && (passWord != sys_passWord)) {
            
            System.out.println("All infos are incorrect!");
            
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For comparison of values within objects you need to use .equals() method. By comparing == within objects Java compares memory addresses.

So the solution for you replace == with .equals().

if ((sys_userName.equals(username)) && (passWord == sys_passWord)) {
    System.out.println("Welcome!");
}

The same for the other if branches.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading