Comparing user id with user id from textfile - java

I want to add user information and reject if user id already exists. Currently, my code displays "ID already Exists!" but still adds the user information.
this is my code:
String id = EditManagerID.getText();
String password = EditManagerPassword.getText();
String name = EditManagerName.getText();
String contact = EditManagerContact.getText();
String address = EditManagerAddress.getText();
String role = EditManagerRole.getText();
try
{
String reader;
BufferedReader br = new BufferedReader(new FileReader("ManagerDetails.txt"));
while ((reader = br.readLine())!=null)
{
String[] split = reader.split(",");
if (id.equals(split[0]))
{
JOptionPane.showMessageDialog(null, "ID already exists!", "Warning", JOptionPane.WARNING_MESSAGE);
}
}
}
catch(Exception e)
{
}
if(id.isEmpty() || password.isEmpty() || name.isEmpty() || contact.isEmpty() || address.isEmpty() || role.isEmpty())
{
JOptionPane.showMessageDialog(null, "Please Fill In Everything!", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
ClassUser u = new ClassUser (id, password, name, address, contact, role);
File f = new File("ManagerDetails.txt");
try(PrintWriter pw = new PrintWriter(new FileWriter(f, true))){
pw.println(u.toString()); //print into txtfile
JOptionPane.showMessageDialog(this, "Added Successfully!");
} catch(Exception e){
JOptionPane.showMessageDialog(null, "Invalid Input!", "Error", JOptionPane.ERROR_MESSAGE);
}
I tried to add an 'if-else' but not sure what to put as a statement.

In your code you 're saying if id already exists show message "ID already exists!" and then you continue adding users info anyway.
In your if id already exists statement set a boolean variable found to true and then make one more if statement and check if found is true or false.
boolean found = false;
// ...
if (id.equals(split[0]))
{
JOptionPane.showMessageDialog(null, "ID already exists!", "Warning",
JOptionPane.WARNING_MESSAGE);
found = true;
//stop the while
break;
}
// ...
//check if id already exists or not. if not then add users info
if(!found){
//put your adding users info code here
}

Related

How can I compare User and password input to a text file?

Heyoo! I'm creating a simple login form using the swing package in java and I am having trouble in checking if the username and password is correct or not.
this here is the code currently:
public void actionPerformed(ActionEvent e) {
try{
File user = new File("Usernames.txt");
File pass = new File("Passwords.txt");
FileReader frUsername = new FileReader(user);
FileReader frPassword = new FileReader(pass);
BufferedReader brUsername = new BufferedReader(frUsername);
BufferedReader brPassword = new BufferedReader(frPassword);
String username = brUsername.readLine();
String password = brPassword.readLine();
if (e.getSource() == btnLogin){
while(username != null && password != null){
if ((txtUsername.getText()).equals(username) && (new String (jpfPassword.getPassword()).equals(password))){
JOptionPane.showMessageDialog(null, "Welcome: " + username, "Login Successful",JOptionPane.INFORMATION_MESSAGE); //this is for testing purposes only
}
else{
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Unable to Login",0); //this is for testing purposes only
}
break;
}
}
brUsername.close();
brPassword.close();
}
catch(IOException err){
System.err.println("File not found.");
}
}
}
The idea is to have multiple accounts stored in the password and usernames files. for example the file content is:
Username.txt:
SampleUsername1
SampleUsername2
Password.txt:
SamplePassword1
SamplePassword2
If line 1 from the username file is "sampleUsername1" then the password for it is also from line 1 "samplePassword1" of the password file. if the user and password isn't the same line or not in the file, it should give an "invalid" error. I know it is not secure to put passwords in a txt file but this is only for practice purposes as I am still learning how to code. Any kind of help and tips is really appreciated. Thanks!
This works fine for me:
public static void main(String[] args) {
String txtUsername = "username2";
String jpfPassword = "password2";
try {
File user = new File("Usernames.txt");
File pass = new File("Passwords.txt");
FileReader frUsername = new FileReader(user);
FileReader frPassword = new FileReader(pass);
BufferedReader brUsername = new BufferedReader(frUsername);
BufferedReader brPassword = new BufferedReader(frPassword);
String username = brUsername.readLine();
String password = brPassword.readLine();
boolean loginSuccess = false;
while (username != null && password != null) {
if ((txtUsername).equals(username) && (jpfPassword.equals(password))) {
JOptionPane.showMessageDialog(null, "Welcome: " + username, "Login Successful", JOptionPane.INFORMATION_MESSAGE); //this is for testing purposes only
loginSuccess = true;
break;
}
username = brUsername.readLine();
password = brPassword.readLine();
}
if (!loginSuccess) {
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Unable to Login", 0); //this is for testing purposes only
}
brUsername.close();
brPassword.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My Usernames.txt and Passwords.txt look like this
username
username1
username2
respectively
password
password1
password2
The main problem was that you were only checking the first line. Once you changed the break; to the readline() methods, the and you can't give the failed message everytime you check a name. That's why you have to loop through everything first, and then check if you failed or not.

Java help me Login with txt File

I do not understand why I always get the result is false !
I tried sysout both input and split []. They are all the same
,Also I can not use this.dispose ()
public void actionPerformed(ActionEvent e) {
String record = null;
FileReader in = null;
try {
in = new FileReader("login.txt");
BufferedReader br = new BufferedReader(in);
String username = txtUser.getText();
String pass = txtPass.getText();
while ((record = br.readLine()) !=null) {
String[] split = record.split(",");
if (username.equals(split[0]) && pass.equals(split[1])) {
JOptionPane.showMessageDialog(null, "YOU IS LOG IN",
"OK", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, "ACCOUNT OR PASSWORD IS NOT ACCURATE",
"False", JOptionPane.WARNING_MESSAGE);
}
// Delete else branch
}
} catch (IOException e) {
e.getCause();
}
}
});
it is login.txt
user,pass
Taka,123
and txtpass is a textfiel normal
Just going out on a limb here as I cannot comment yet, but it might have to do with your inclusion of user,pass in the login.txt file. Try to remove that line so the file starts with the actual user and password.
Also, I'm not sure about the use of this code, but storing passwords in a plaintext file is never a good idea.

Java-Swing: Can't trap user into typing a correct filename

I'm trying to trap a user into typing a correct file name unless he presses cancel or X. But if he does cancel the input my program throws a NullPointerException.
public void openSaveAsDirectory() {
JDialog dialog = new JDialog();
dialog.setTitle("Save file as");
String name = JOptionPane.showInputDialog(adTable, "Please type a name for your file");
if(name != null && !name.isEmpty()) {
File fileName = new File(SAVE_LOCATION + FILE_SEPERATOR + name + FILE_SUFFIX);
book.saveUser(fileName);
}
while(name.isEmpty()) {
name = JOptionPane.showInputDialog(adTable, "Please type a name for your file");
}
}
Based on your comment, here is an updated version that asks for an input as long as it is empty but stops, when the user hits the cancel button.
String name;
do {
name = JOptionPane.showInputDialog(null, "Please type a name for your file");
if(name == null) { //user hit cancel, break the loop
break;
}
} while(name.isEmpty());

Java: getting info from a specific line in files

I have made this nice login program with all usernames in one .txt file and all passwords in the other. so when the user enters a username and it corresponds to one of the names on for example line 5 of the first file, I want the program to read the password from the 5th line in the second file and see if it matches with the password given by the user. I just don't know how to read from a specific file or how to see on what line it is,
here is the code I have now.
package databarry_;
import java.util.*;
import java.io.*;
import java.lang.*;
import javax.swing.JOptionPane;
public class interfacelogin {
public static void main (String[] args) {
boolean check1=false, check2=false, check3=false;
int trys = 3;
while (check3 == false){
int id1 = 0;
int id2 = 0;
String username = null;
String password = null;
Scanner fileout = null;
Scanner fileout2 = null;
try{
fileout = new Scanner(new File("username.txt"));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Fatal Error, please Reboot or reinstal program", "Boot", JOptionPane.PLAIN_MESSAGE);
}
String Username = JOptionPane.showInputDialog("Please enter your username");
while(fileout.hasNext()){
username = fileout.next();
if(Username.equals(username))
check1=true;
}
try{
fileout2 = new Scanner(new File("password.txt"));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Fatal Error, please Reboot or reinstal program", "Boot", JOptionPane.PLAIN_MESSAGE);
}
String Password = JOptionPane.showInputDialog("Please enter your username");
while(fileout2.hasNext()){
password = fileout2.next();
if(Password.equals(password) && id1 == id2)
check2=true;
}
if (check1 == true && check2 == true){
JOptionPane.showMessageDialog(null, "succeded", "login", JOptionPane.PLAIN_MESSAGE);
check3 = true;
} else {
if (trys > 1){
trys--;
JOptionPane.showMessageDialog(null, "bad login, you have " + trys + " try's remaining", "login", JOptionPane.PLAIN_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "To many bad logins, program is closing", "login", JOptionPane.PLAIN_MESSAGE);
check3 = true;
}
}
}
}
}
as you can see the only big flow is that if you enter a password and username that ar not on the same line (so not linked to each other) in the files (like both on line 5) the user gets trough.
Best way to do so is to read both files and store your login/password pairs in a
HashMap<String, String>
Then you can easily check, if entered login-password pair is a match.
Map<String, String> map = new HashMap<>();
while(fileout.hasNext() && fileout2.hasNext()){
username = fileout.next();
password = fileout2.next();
map.put(username, password);
}
...
if (password.equals(map.get(username)) {
...
}
If you don't have problems with memory, or if the amount of users is not so high, I suggest you to read together both files only once when the program starts, and store the data in a HashMap using the user as key and the password as value:
BufferedReader users = new BufferedReader(new FileReader("username.txt"));
BufferedReader passwords = new BufferedReader(new FileReader("password.txt"));
HashMap logins = new HashMap<String, String>();
String user,pass;
while ((user=users.readLine())!=null) {
pass=passwords.readLine();
logins.put(user, pass);
}
and then to check a username/password:
String username = null; //the username specified by the user
String password = null; //the password specified by the user
if (logins.get(user).compareTo(password)==0) {
//correct pass
} else {
//wrong pass
}
This is only a sketch to give you and idea (it does not consider special cases, as the user insert a username that does not exists, and so on...)

Pass a string from one class to another in java

I'm trying to pass a String from one class to another class but the result I'm getting is 'null'. I want to pass the String username from LoginFrame to HomeworkFrame;
HomeworkFrame:
public void loadSubjects (){
String item;
try{
System.out.println(username);
Scanner f = new Scanner (new FileReader (username + " " + "Subjects" + ".txt"));
while(f.hasNext()){
item = f.nextLine();
chSubjects.add(item);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Subjects cannot be loaded!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
LoginFrame:
public void loginUser(){
r = new Registration();
h = new HomeworkFrame();
l = new Login();
l.username = txtUser.getText();
l.password = txtPass.getText();
try{
String line;
boolean passwordFound = false ;
BufferedReader f = new BufferedReader(new FileReader(l.username + ".txt"));
while((line = f.readLine()) != null){
if(line.equals(l.password)){
passwordFound = true;
}
}
if(passwordFound){
h.username = l.username;
dispose();
m.setSize(700,600);
m.setLocation(100,100);
m.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Obviously I'm getting the error "Subjects cannot be loaded" as the username is null(I checked it by using the println method).
In case problems like this you have to track your variables/fields from the place you've noticed your 'username' field is null. Next steps should be:
Check what operations you do on 'h' object before you call the loadObjects() method and if any then check what influence they have on username field in HomeWorkFrame (using println or a debugger).
Check if your passwordFound in LoginFrame is true (because if it's false it doesn't assign a value to h.username)
If it's false check if your password's been retrieved from a file (using same println statement)
This kind of scenario should help you finding most of 'null' bugs.
Try to check first, which type of Exception you get.
May be the file is not existing or the list is null or....
Is a format problem : put a \ before your space in pathString : "\ "
You have to write it "\ Subjects.txt", without '+' between.
public class LoginFrame{
private HomeworkFrame hw;
public void doSomething(){
String username = "your username";
hw = new HomeworkFrame(username);
}
}
public class HomeworkFrame{
public HomeworkFrame(String username){
doSomething with 'username'
}
}
Ans to your question! :)
If System.out.println(username); displays null this means that
1.username variable is not initialized and left.
2.value is not assigned to it properly.
3.It might be a static variable and you are changing the value of it.
Please check all these conditions and please give that part of the code from where the loadSubjects() is being called, and not the body of that method as you have provioded it already.
Also all those parts of code where the username is initialized,assigned,modified.
It is required to specify or pass the value otherwise it will definitely give Null as it will not find any value to execute.

Categories

Resources