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;
}
}