This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
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;
}
}
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()
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).
Related
I have been working on this program and have recently came to an error using a static method.
I don't normally use static methods but they are in the requirements.
So i have a static method VerifyUserNameAndPassWord which takes an input of a list of users and a user name and password and compares it to the ones stored in the object to see if the details are correct.
Unfortunately with this method it only ever recognized "User1" (Thefirst object) and any time i try to put in user2's username and password it always throws the illegal argument error i put in.
User 2 is stored in the array list of course.
This is my main method:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your user name");
String userName = scanner.nextLine();
System.out.println("Enter your password name");
String passWord = scanner.nextLine();
if(User.verifyLoginByUsernameAndPassword(userList, userName, passWord)== true)
{
do something..
}
And this is the static method:
public static boolean verifyLoginByUsernameAndPassword(ArrayList<User> user, String username, String password)
{
boolean check = false;
for(User s: user)
{
if(username.equals(s.getUserName()) && password.equals(s.getPassWord()))
{
check = true;
break;
}
else
{
check = false;
throw new IllegalArgumentException("Username and password are incorrect ");
}
}
return check;
}
Change your method implementation. Check the entire list then throw exception if username and passwords not matched.
public static boolean verifyLoginByUsernameAndPassword(ArrayList<User> user, String username, String password) {
for(User s: user) {
if(username.equals(s.getUserName()) && password.equals(s.getPassWord())) {
return true;
}
}
throw new IllegalArgumentException("Username and password are incorrect ");
}
so I know that there are many similar questions to mine but i do not really understand what they mean as i am not that great when it comes to coding.
my login screen in the GUI is this:
public void createLoginPanel()
{
loginPanel.setLayout(null);
loginLbl.setLocation(425,50);
loginLbl.setSize(500,50);
loginLbl.setText("Login");
loginPanel.add(loginLbl);
usernameLbl.setLocation(250,300);
usernameLbl.setSize(250,50);
usernameLbl.setText("Username: ");
loginPanel.add(usernameLbl);
usernameTxt.setLocation(350,300);
usernameTxt.setSize(250,50);
usernameTxt.setText("");
usernameTxt.setColumns(10);
loginPanel.add(usernameTxt);
passwordLbl.setLocation(250,400);
passwordLbl.setSize(250,50);
passwordLbl.setText("Password: ");
loginPanel.add(passwordLbl);
passwordTxt.setLocation(350,400);
passwordTxt.setSize(250,50);
passwordTxt.setText("");
passwordTxt.setColumns(10);
loginPanel.add(passwordTxt);
loginBtn.setLocation(675,400);
loginBtn.setSize(100,50);
loginBtn.addActionListener(this);
loginBtn.setText("Login");
loginPanel.add(loginBtn);
gotoWelcomeScreenBtn2.setLocation(100,600);
gotoWelcomeScreenBtn2.setSize(150,50);
gotoWelcomeScreenBtn2.addActionListener(this);
gotoWelcomeScreenBtn2.setText("Home");
loginPanel.add(gotoWelcomeScreenBtn2);
}
the login i currently have is this:
if(e.getSource() == loginBtn)
{
String pass;
String user;
user = usernameTxt.getText();
pass = passwordTxt.getText();
if(user.equals("username") && pass.equals("pass") )
{
JOptionPane.showMessageDialog(null,"Login successful");
allTheGUITabs.setSelectedIndex(7);
}
else
{
JOptionPane.showMessageDialog(null,"Please try again.");
}
System.out.println("Login Button pressed");
}
i want to login using existing info that i have stored in a text file called "employeelist.txt" and i am not sure how to do this.
edit: i have changed the login to user.equals and pass.equals but i am still unsure on how to login with anything other than what i've declared.
edit:
this is the contents of my text file. the second is the username and the third is the password. how will i scan this text file to ensure that the username and password match?
1,MSmith01,Pass123,Mark Smith,12 Yellow Lane,L34GF4,07837463
2,JSmith02,Pass456,Joan Smith,8 Green Road,L394RQ,08765456765
3,PSmith03,Pass678,Paul Smith,9 Orange Street,L435RE,07485747362
4,WSmith04,Pass910,Walter Smith,8 Green Road,L394RQ,08765456765
5,CSmith05,Pass149,Callum Smith,12 Yellow Lane,L34GF4,07485848373
6,MSmith06,Pass213,Mark Smith,32 Red Road,L384GT,07874636472
7,TMath07,Pass141,Terry Matthews,4 Peach Street,L219RB,07564737283
Let’s say you have next strings in your txt file
admin
qwerty12345
Use scanner and pass values for your variables reading them from txt
File employeelist;
Scanner scanner;
String login;
String password;
try
{
employeelist = new File("employeelist.txt"); // changed code
scanner = new Scanner(employeelist); //changed code
while(scanner.hasNextLine())
{
login = scanner.nextLine();
password = scanner.nextLine();
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}
Then use it in your if statement.
if(user.equals(login) && pass.equals(password)
{
// your code here
}
I'm having issue returning the DVDs object after adding the second while loop (promptAddAgain). This function works perfect before this while loop was added. Error during compile - cannot find symbol: variable currentDVD.
public DVDs getNewDVDInfo() {
boolean keepRunning = true;
boolean promptAddAgain = true;
while (keepRunning) {
String title = input.readString("Please enter the move title.");
String releaseDate = input.readString("Please enter the release date.");
String MPAArating = input.readString("Please enter the MPAA rating.");
String directorName = input.readString("Please enter the director name.");
String studio = input.readString("Please enter the name of the studio.");
String userRating = input.readString("Please type in any comment you would "
+ "like to leave for this movie below.");
DVDs currentDVD = new DVDs(releaseDate, MPAArating, directorName, studio, userRating);
currentDVD.setTitle(title);
while (promptAddAgain) {
String userAns = input.readString("Would you like to add another DVD to the library?");
if (userAns.equals("n")) {
input.print("Thank you. Returning to main menu.");
keepRunning = false;
promptAddAgain = false;
} else if (userAns.equals("y")) {
input.print("\n");
} else {
input.print("Unknown input, please try again.");
keepRunning = false;
}
}
}
return currentDVD; //<--- error
}
The error is arising because currentDVD is currently being defined inside the outer while loop, but you are referring to it outside that loop, after it has gone out of scope. One way to fix this is to declare currentDVD before the first while loop:
DVDs currentDVD = null;
while (keepRunning) {
...
}
return currentDVD;
Keep in mind that with the above approach it is possible that your getNewDVDInfo() method might return null, so callers should be aware of that.
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.
Hello i am a new java student i have been working on a library system containing ( users - library workers and books ) so i am trying to create a log in form i already have an array list but i did a file stream ( to clarify i let the new user to register and his/her information will be saved to the file like this ID Name Password Age ) so i have tried to do something as this method in the library users class
private Scanner x;
private String user_name , password ;
public void openfile(){
try {x= new Scanner (new File ("E:\\javaapplication1
\\test\\professors.txt"));
}
catch(Exception e){
System.out.println("couldn't find file");
}
}
public void checklog ( String username , String password ){
String a , b ,c ,d ;
while(x.hasNext()){
a = x.next();
b = x.next();
c = x.next();
d = x.next();
if ( b == username ||c == password ){
System.out.println("Loggin successful ");
}
else
System.out.println("Loggin failed wrong id or password ");
break;
and then call it like this in the main with the full code
System.out.println ("Enter your name ");
check_name = reader.next();
System.out.println ("Enter your password ");
check_password =reader.next();
lib_us professor ;
professor = new lib_us();
professor.openfile();
professor.checklog(check_name, check_password);
i get all passwords wrong i save them like 4 id name password and age that's why i created a b c and d ...
i am still new in this kind of log in forms so please specify me a solution and if you need the whole code please ask for it :)
So in your checkLog() method you have the statement if(b == username || c == password) should be if(b.equals(username) && c.equals(password)) OR if(b.equalsIgnoreCase(username) && c.equalsIgnoreCase(password)) for case sensitive or not (use the equals() method for case sensitivity or the equalsIgnoreCase() method for non case sensitivity).
Understand why that is? Because in your original statement you are saying only one of them has to be true in order for it to be a successful login. With the revised one both of them must be true. Also you should not use the operator == to compare two strings to see if they are the same string. That will only compare their addresses.
EDIT:
If your file is kind of like what is shown below:
12 Name Pass 12
13 Namez Passz 13
14 Namezz Passzz 14
Try this code to read it in and compare:
private Scanner x;
private String user_name, password;
public void openFile()
{
try
{
x = new Scanner(new File("FILE PATH"));
}
catch(Exception e)
{System.out.println("Couldn't find file"); System.exit(0);}
}
public boolean checklog(String username, String password)
{
String temp;
String[] info;
while(x.hasNext())
{
temp = x.nextLine();
info = temp.split(" ");
//info[0] = id, info[1] = username, info[2] = password, info[3] = age;
//Right here that means the username and password is correct
if(info[1].equals(username) && info[2].equals(password))
{
System.out.println("Login Successful");
return true;
}
}
System.out.println("Login failed wrong id or password");
return false;
}