-1

I have a small snippet of code that is supposed to check the inputted codename and password against what is stored in a text file. If there is a match, it will start the game and everything is fine. But if there is no match, a dialog is supposed to pop up asking the user if they want to try logging in again.

int input=0; //yes

do {
    codename=JOptionPane.showInputDialog(null,"Enter Codename: ");
    String password=JOptionPane.showInputDialog(null, "Enter Password: ");

    for(int i=0;i<users.length;i++){
        if((codename.equals(users[i].getCodeName())) && (password.equals(users[i].getPassword()))){
            System.out.println("\n\nCorrect");
            new Game();
        } else {
            System.out.println("\n\nIncorrect");
        }   
    }
    input = JOptionPane.showConfirmDialog(null, "Incorrect User name/Password\nWould you like to try again?");          
} while(input==0); //run while input is yes

The problem: the code after the for loop does not execute. If I check the variables against users[i] the code after the for loop does not run, but if I check against users[2] for example, then it works fine.

Not sure if this matters but I always get this error:

Exception in thread "main" java.lang.NullPointerException
    at com.ramtin.Game.logOn(Game.java:505)
    at com.ramtin.Game.main(Game.java:397)

I get it even when the password and codename match and the program runs perfectly.

FULL CODE for the above code:

    public static void logOn(){
        //ASK FOR CODENAME & PASSWORD FROM TEXTFILE BEFORE GAME BEGINS
        //read from text file

        UserData[]users=new UserData[20];
        int countU=0;

        try{
            BufferedReader readU = new BufferedReader(new FileReader("userdata.txt"));

            String line;

            while((line=readU.readLine())!=null){
                String []parts=line.split("#");

                String codeName = parts[0];
                String password=parts[1];

                //              System.out.println(parts[0]);
                //              System.out.println(parts[1]);
                users[countU]=new UserData(codeName, password);
                countU++;
            }
            readU.close();
        }
        catch(FileNotFoundException e){

        }
        catch(IOException e){

        }

        //PASSWORD & CODENAME

        int input=0; //yes

        do{
            codename=JOptionPane.showInputDialog(null,"Enter Codename: ");
            String password=JOptionPane.showInputDialog(null, "Enter Password: ");

            for(int i=0;i<users.length;i++){
                if((codename.equals(users[i].getCodeName()))&&(password.equals(users[i].getPassword()))){
                    System.out.println("\n\nCorrect");
                    new Game();
                }
                else{
                    System.out.println("\n\nIncorrect");
                }   
            }

            input = JOptionPane.showConfirmDialog(null, "Incorrect Username/Password\nWould you like to try again?");           
        }
        while(input==0); //run while input is yes
    }
}

FULL CODE for UserData:

public class UserData {

    private String codename;
    private String password;

    UserData (String codeName, String password)
    {
        this.codename = codeName;
        this.password= password;
    }


    String getCodeName()
    {
        return codename;
    }


    String getPassword()
    {
        return password;
    }


    public String toString ()
    {
        String temp = "\nCode name: "+codename+"\nPassword: " + password;
        return temp;
    }
    }
badProgrammer
  • 17
  • 1
  • 12
  • What does the users array look like? Sounds like its throwing an exception because the users before index 2 doesnt contain what you think it does. what does the console say after it finishes running? – Master Yoda Sep 21 '17 at 17:19
  • @MasterYoda It says this when the password/codename is wrong: java.lang.NullPointerException at com.ramtin.Game.logOn(Game.java:505) at com.ramtin.Game.main(Game.java:397) It also says the same thing when it is correct, but it starts the game and everything works fine. The users array is made up of a class diagram that holds a String codename and a String password variable. – badProgrammer Sep 21 '17 at 17:24
  • Is one of the lines on the screen 397 or 505? – JensS Sep 21 '17 at 17:27
  • This isnt the full code, please post the users array along with an example of its contents – Master Yoda Sep 21 '17 at 17:30
  • Are you saying that `String name = users[i].getCodeName()` doesn't work but `String name = users[2].getCodeName()` does? – geneSummons Sep 21 '17 at 17:30
  • @MasterYoda Yes, the first if statement in the for-loop is line 505. Line 397 is in main(), it simple calls for this method that handles the login. – badProgrammer Sep 21 '17 at 17:32
  • @geneSummons Yes, for some reason, in the if statement when I use 'i' it doesn't execute after the loop. But normally when a for-loop is complete, the code after should be executed, but in my case it doesn't. – badProgrammer Sep 21 '17 at 17:34
  • @MasterYoda I posted the full code for the method and the class diagram for the user array. – badProgrammer Sep 21 '17 at 17:42
  • Step through your code with a debugger and inspect the `users` array. My guess is that your `BufferedReader` loop terminates just shy of filling the array, thus making the rest null. – Jonathan Sudiaman Sep 21 '17 at 17:44
  • Possible reasons: in your file are less than 20 users, one line does not have the separator (#) in it (or is empty) or a user or his/her password are null. – JensS Sep 21 '17 at 17:47
  • @JensS The file does have less than 20 users (4 to be exact), but none are null and they all have the # delimiter separating the codename and the password. – badProgrammer Sep 21 '17 at 17:49
  • @Sudicode Could you please explain? I have it loop until users.length, therefore it should check the whole array. – badProgrammer Sep 21 '17 at 17:51
  • @NikolasCharalambidis I had already checked for that and I am unable to spot the problem. Nothing should be null in the method. – badProgrammer Sep 21 '17 at 17:52

2 Answers2

0

Don't do for(int i=0;i<users.length;i++){

Do do for(int i=0;i<countU;i++){

Every array element after countU will cause NPE when you call a method on a null element like users[i].getCodeName()

geneSummons
  • 907
  • 5
  • 15
  • Thank you so much! That solved the issue. I can't believe I made such a silly error. But now I have the issue that it still shows the JOptionPane saying the password is wrong over the game that started. I made the while loop only run if the input = 0. So not sure why it does that. Any solution for that? – badProgrammer Sep 21 '17 at 18:02
  • `input` is always zero until it changes (if it changes) after the "bad password" option dialog is shown. – geneSummons Sep 21 '17 at 18:12
  • **EDIT** Solved the pop up issue. Just had to break out of the do while loop. Thanks again for the help. – badProgrammer Sep 21 '17 at 18:13
0

Instead of using an array with the length 20, you can use an ArrayList as it will expand dynamically:

List<UserData> users = new ArrayList<>();

Then add each userdata to the list

users.add(new UserData(codeName, password));

and iterate with

for(int i=0 ;i<users.size(); i++) {

This will prevent the NullPointer as you only have as many entries as you have users (and will also dynamically grow/shrink with the number of users you have).

JensS
  • 1,151
  • 2
  • 13
  • 20