I have a simple problem.
I'm trying to create a registration program using text files in java.
I wrote some code to do registration but at first my program should check if username is exists in text file or not.
If username is exists then the program asks user to enter new one.
But there is some error in my code i don't know, it is not checking if username exists or not.
here is my code:
System.out.println("Registration Page");
System.out.println("NOTE: your username is a unique one so it cannot be changed.");
System.out.printf("Username: ");
String user = input.next();
System.out.printf("Password: ");
String pass = input.next();
System.out.printf("Confirm Password: ");
String conf = input.next();
int length = pass.length();
int passInt = Integer.parseInt(pass);
int confInt = Integer.parseInt(conf);
if(length < 6)
System.out.println("Too short password, password must be 6 characters or more");
else
{
if(passInt == confInt)
{
Scanner z = null;
try{
z = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt"));
boolean checkname = false;
while(z.hasNext())
{
String a = z.next();
int b = z.nextInt();
if(a == null ? user == null : a.equals(user))
checkname = true;
}
if(checkname)
System.out.println("Username is already exists and used, please type another one");
else
{
Formatter x = null;
try{
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\accounts.txt", true);
x = new Formatter(f);
x.format("%s %s%n",user.toUpperCase(),pass);
System.out.println("You registered succesfully");
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
catch(Exception e){}
}
else
System.out.println("Password and confirm password are not matching");
}
So instead of using Scanner to open and read the file, try using BufferedReader and Writer respectively for the reading and writing. In the code below we are reading through the file and if the name exists it will change your boolean to true and will then throw your error, otherwise it will complete the registration. It also will write the new information. Now one thing you may want to add is a way to loop back to the top if the information is invalid.
Also as a side not, for better cross OS functionality, you should use File.separator() which will do the same thing.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Registration Page");
System.out.println("NOTE: your username is a unique one so it cannot be changed.");
System.out.printf("Username: ");
String user = input.next();
System.out.printf("Password: ");
String pass = input.next();
System.out.printf("Confirm Password: ");
String conf = input.next();
int length = pass.length();
int passInt = Integer.parseInt(pass);
int confInt = Integer.parseInt(conf);
File file = new File("C:"+File.separator + "Users"+File.separator + "فاطمة"+File.separator + "Downloads"+File.separator + "accounts.txt");
if (length < 6) {
System.out.println("Too short password, password must be 6 characters or more");
} else {
if (passInt == confInt) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String current;
boolean checkname = false;
while ((current = br.readLine()) != null) {
if(current.equalsIgnoreCase(user)){
checkname = true;
}
}
if (checkname) {
System.out.println("Username is already exists and used, please type another one");
} else {
Formatter x = null;
try {
FileWriter f = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(f);
bw.write(user);
bw.close();
x = new Formatter(f);
x.format("%s %s%n", user.toUpperCase(), pass);
System.out.println("You registered succesfully");
x.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
}
} else {
System.out.println("Password and confirm password are not matching");
}
}
}
}
I have found what is the problem with my code:
the problem is that the username is found in the text file in this format:
JOHN 114477
SARAH 887755
The username is in uppercase letters and when i enter new username it's written in lower case letters so when searching for username in the text file the program compares name in lowercase letters with a name in uppercase letters that are not matching and so it allows me to enter the same username that exists before.
the correct solution is by editing this line and adding toUpperCase(); to it like this:
String user = input.next().toUpperCase();
Related
There are two files, one is userData.txt and the other one is gameData.txt. In my program, I give two options to the user. Login and Register. If the user clicks on the Register option, then I ask for the ID and password they'd like to keep and store them in userData.txt. Then I run a command which generates a random string which will be stored with the user's credentials in userData.txt as well as in the gameData.txt. After the unique token is written in gameData.txt, I will assign 0 coins as default. This is how it will look like:
Akshit, Joshi, 687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b (in userData.txt)
687fd7d1-b2a9-4e4a-bc35-a64ae8a25f5b, 0 (in gameData.txt)
Now, if a user clicks on Login option, then the program verifies the data from userData.txt. It also reads the unique token after the credentials and then stores it into a variable named uniUserID.
Now comes the part where I am stuck. I compare this uniUserID to the data in the gameData.txt file. The Scanner reads the gameData.txt line by line and compares the uniUserID with it. What I want is, if it finds the ID then it should read the coins after it (which is 0) and store it into a variable named coins. But it throws me an error that goes like, "NoSuchElementException"
Here is the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;
public class Verification
{
static File credentials = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
static String uniUserID = " ";
static File gameData = new File ("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");
public boolean Verify (String ID,String Pass)
{
String tempName = " "; //the data read from the .txt file would be stored in these temporary variables
String tempPass = " ";
boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
boolean verified = false;
try //Try and catch block is initialized in case the file is not found
{
do
{
Scanner s2 = new Scanner(credentials); //Reading the .txt file
s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
while (s2.hasNext() && !found)
{
tempName = s2.next(); //assigning the data read from the file to these variables
tempPass = s2.next();
uniUserID= s2.next();
if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
{
verified = true;
found = true;
}
}
}
while (found = false);
}
catch (Exception ex)
{
System.out.println("Error");
}
return verified;
}
public void Write (String newUser, String newPass) {
String uniID = " ";
try {// try catch is used in case the file is not found
uniID = UUID.randomUUID().toString();
FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
BufferedWriter buffwrite = new BufferedWriter(writer); // creating buffered writer object
buffwrite.write("\n"); // Writing the new user's credentials into the .txt file
buffwrite.write(newUser);
buffwrite.write(",");
buffwrite.write(newPass);
buffwrite.write(",");
buffwrite.write(uniID);
buffwrite.close();
} catch (Exception ex) {
System.out.println("Error");
}
try
{
FileWriter writer2 = new FileWriter(gameData, true);
BufferedWriter buffwrite2 = new BufferedWriter(writer2);
buffwrite2.write("\n");
buffwrite2.write(uniID);
buffwrite2.write(",");
buffwrite2.write("0");
buffwrite2.close();
}
catch(Exception ex)
{
System.out.println("Error");
}
}
public static void Game(String uniqueID) throws FileNotFoundException
{
Scanner s3 = new Scanner (gameData);
String waste = " ";
String coins = " ";
while (s3.hasNextLine())
{
String fileLine = s3.nextLine();
if(fileLine.contains(uniUserID))
{
s3.useDelimiter(("[\n]"));
s3.skip(uniUserID);
coins = s3.next();
}
}
System.out.println(coins);
}
public static void main(String[] args) throws FileNotFoundException {
Verification obj = new Verification();
Scanner s1 = new Scanner(System.in); //Creating scanner object
boolean end = false; //declaring the variable that will end the do while loop
do //do while loop is used so that the user gets taken to the main menu again and again
{
System.out.println("Welcome to the economic bot!");
System.out.println("Select one option to proceed");
System.out.println("1. Login");
System.out.println("2. Register");
int choice = s1.nextInt(); //accepting user's choice
switch (choice) {
case 1:
System.out.println("Enter your username:");
String userID = s1.next(); //taking user credentials
System.out.println("Enter your password");
String userPass = s1.next();
boolean validated = obj.Verify(userID,userPass);
if (validated == true) { //if the login details are correct
System.out.println("Login Successful!");
System.out.println("Redirecting...");
System.out.println();
end = true;
Game(uniUserID);
}
else { //if the details entered are wrong
System.out.println("Login failed! Possibly due to wrong user credentials.");
System.out.println("Please try again!");
}
break;
case 2:
System.out.println("Enter the username you'd like to keep:");
String regUserID = s1.next(); //accepting user details
System.out.println("Enter the password:");
String regUserPass = s1.next();
obj.Write(regUserID,regUserPass);
break;
default:
System.out.println("Invalid Option chosen."); // In case the user enters a wrong choice
}
}
while (!end); // condition for the initial do loop
}
}
Try the below code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.UUID;
public class Verification {
static File credentials = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\userData.txt"); //Clarifying filepath
static String uniUserID = " ";
static File gameData = new File("C:\\Users\\user\\IdeaProjects\\Economic Bot\\out\\gameData.txt");
public boolean Verify(String ID, String Pass) {
String tempName = " "; //the data read from the .txt file would be stored in these temporary variables
String tempPass = " ";
boolean found = false;//declaring some boolean variables so that the do while and if else statements work smoothly
boolean verified = false;
try //Try and catch block is initialized in case the file is not found
{
do {
Scanner s2 = new Scanner(credentials); //Reading the .txt file
s2.useDelimiter("[,\n]");// The file reader will stop once it encounters any of the following delimiters
while (s2.hasNext() && !found) {
tempName = s2.next(); //assigning the data read from the file to these variables
tempPass = s2.next();
uniUserID = s2.next();
if (tempName.trim().equals(ID) && tempPass.trim().equals(Pass))//comparing the data read from the file and the data entered by the user
{
verified = true;
found = true;
}
}
}
while (found = false);
} catch (Exception ex) {
System.out.println("Error");
}
return verified;
}
public void Write(String newUser, String newPass) {
String uniID = " ";
try {// try catch is used in case the file is not found
uniID = UUID.randomUUID().toString();
FileWriter writer = new FileWriter(credentials, true);// initializing the FileWriter, to make sure that it doesn't overwrite true is used so that it appends
BufferedWriter buffwrite = new BufferedWriter(writer); // creating buffered writer object
buffwrite.write("\n"); // Writing the new user's credentials into the .txt file
buffwrite.write(newUser);
buffwrite.write(",");
buffwrite.write(newPass);
buffwrite.write(",");
buffwrite.write(uniID);
buffwrite.close();
} catch (Exception ex) {
System.out.println("Error");
}
try {
FileWriter writer2 = new FileWriter(gameData, true);
BufferedWriter buffwrite2 = new BufferedWriter(writer2);
buffwrite2.write("\n");
buffwrite2.write(uniID);
buffwrite2.write(",");
buffwrite2.write("0");
buffwrite2.close();
} catch (Exception ex) {
System.out.println("Error");
}
}
public static void Game(String uniqueID) throws FileNotFoundException {
Scanner s3 = new Scanner(gameData);
String waste = " ";
String coins = " ";
while (s3.hasNextLine()) {
String fileLine = s3.nextLine();
if (fileLine.contains(uniUserID)) {
/*s3.useDelimiter(("[\n]"));
s3.skip(uniUserID);
coins = s3.next();*/
coins = fileLine.split(",")[1];
break;
}
}
System.out.println(coins);
}
public static void main(String[] args) throws FileNotFoundException {
Verification obj = new Verification();
Scanner s1 = new Scanner(System.in); //Creating scanner object
boolean end = false; //declaring the variable that will end the do while loop
do //do while loop is used so that the user gets taken to the main menu again and again
{
System.out.println("Welcome to the economic bot!");
System.out.println("Select one option to proceed");
System.out.println("1. Login");
System.out.println("2. Register");
int choice = s1.nextInt(); //accepting user's choice
switch (choice) {
case 1:
System.out.println("Enter your username:");
String userID = s1.next(); //taking user credentials
System.out.println("Enter your password");
String userPass = s1.next();
boolean validated = obj.Verify(userID, userPass);
if (validated == true) { //if the login details are correct
System.out.println("Login Successful!");
System.out.println("Redirecting...");
System.out.println();
end = true;
Game(uniUserID);
} else { //if the details entered are wrong
System.out.println("Login failed! Possibly due to wrong user credentials.");
System.out.println("Please try again!");
}
break;
case 2:
System.out.println("Enter the username you'd like to keep:");
String regUserID = s1.next(); //accepting user details
System.out.println("Enter the password:");
String regUserPass = s1.next();
obj.Write(regUserID, regUserPass);
break;
default:
System.out.println("Invalid Option chosen."); // In case the user enters a wrong choice
}
}
while (!end); // condition for the initial do loop
}
}
Suggestions:
Try adding a new line (\n) character at the end of every line not at the beginning because it is adding a blank line at the start of the files.
Break the loop if the id matching is found.
Change the Game() method to this:
{
Scanner s3 = new Scanner (gameData);
String waste = " ";
String coins = " ";
while (s3.hasNextLine())
{
String fileLine = s3.nextLine();
if(fileLine.contains(uniUserID))
{
coins = fileLine.split(",")[1];
break;
}
}
System.out.println(coins);
}
Simply split the line in 2 parts using a divider (,) and get the second part where are contained the coins
To add more coins, use a BufferedWriter:
BufferedWriter writer = new BufferedWriter(new FileWriter(gameData));
writer.write(uniId+","+newCoins);
writer.close();
Important: remove true from the FileWriter object because you are overwriting and not appending
I am currently working on a project assigned to me by my teacher where I need to login a user into my system using;
first the user register the data is stored in file using arraylist(MUST INCLUDE part of assignment) this part working fine the code for this i use is;
ArrayList<data> regUser = new ArrayList<data>();
public void regUser() {
String regName = JOptionPane.showInputDialog(null, "Enter User Name:");
String regPass = JOptionPane.showInputDialog(null, "Enter User Password:");
data p = new data(regName, regPass);
regUser.add(p);
for (int i = 0; i < regUser.size(); i++) {
try {
FileWriter writer = new FileWriter("C:\\Users\\Desktop\\outputFile.txt", true);
PrintWriter pw = new PrintWriter(writer);
pw.println(regUser.get(i));
pw.close();
writer.close();
} catch (IOException e) {
System.out.println("File not found");
}
}
JOptionPane.showMessageDialog(null, "User registered successfully");
}
Now the user has to login from the data in file in same way first data from file is entered in arraylist then it is matched with user entered data but im having issues;
public void login() {
ArrayList<String> loginUser = new ArrayList<>();
String name = JOptionPane.showInputDialog(null, "Enter User Name:");
String password = JOptionPane.showInputDialog(null, "Enter User Password:");
try {
FileReader fr = new FileReader("C:\\Users\\Desktop\\outputFile.txt");
BufferedReader br = new BufferedReader(fr);
String st;
while ((st = br.readLine()) != null) {
loginUser.add(st);
}
// System.out.println(loginUser);
br.close();
fr.close();
} catch (IOException e) {
System.out.println("File not found");
}
for (int i = 0; i < loginUser.size(); i++) {
if (loginUser.get(0).equals(name) && loginUser.get(1).equals(password)) {// help need for find a condition here
JOptionPane.showMessageDialog(null, "Welcome to Rent A Car");
return;
}
}
JOptionPane.showMessageDialog(null, "Wrong login info please try again");
}
Im not that much expert in arraylist so if someone can guide me a bit will really appreciate thanks in advance
the data in my outputfile.txt is for now:
helo 123
test 456
You are obtaining the line from the file correctly, but you have to split the parts of the line, in this case split by space character, so that you can obtain the username and the password of the user separately. First, You will probably want to have username and password on each line in your text file, so that you can extract exactly 1 username and 1 password per read line in your while loop, e.g. of outputfile.txt:
helo 123
test 456
We'll assume that this will always work as expected (=a line in the file will always contain only the username and password separated by a space character). In a serious project you definitely shouldn't assume that and you should use a data store of some kind.
You can then achieve the splitting of each line in your while loop like this:
String[] credentials = st.split(" ");
credentials will hold 2 elements, which will be the username and password (e.g. credentials[0] = "helo" and credentials[1] = "123").
You can then do the following in your while loop to add the credentials to the ArrayList and to then match the strings added to the list, whether they match:
public void login()
{
ArrayList<String> loginUser=new ArrayList<>();
String name = JOptionPane.showInputDialog(null, "Enter User Name:");
String password = JOptionPane.showInputDialog(null, "Enter User Password:");
try {
FileReader fr=new FileReader("C:\\Users\\Desktop\\outputFile.txt");
BufferedReader br=new BufferedReader(fr);
String st;
while ((st = br.readLine()) != null)
{
// This changed
String[] credentials = st.split(" ");
for (String credential : credentials) {
loginUser.add(credential);
}
}
br.close();
fr.close();
}
catch(IOException e)
{
System.out.println("File not found");
}
// This for block changed
for (int i = 0; (i + 1) < loginUser.size(); i += 2) {
String uname = loginUser.get(i);
String pass = loginUser.get(i + 1);
if (uname.equals(name) && pass.equals(password)) {
JOptionPane.showMessageDialog(null, "Welcome to Rent A Car ");
return;
}
}
JOptionPane.showMessageDialog(null, "Wrong login info please try again");
}
The above code assumes your username is the first set of characters in the file and the password the second set of characters in the file, where username and password are separated by a space characters. The i in the for loop increments by 2, because 0 = username, 1 = password; 3 = username, 4 = password etc. The (i + 1) < loginUser.size(); is a precaution check to verify that there are next 2 elements (username and password).
It's a pretty nasty code with an ArrayList, but if it's a must for the assignment, then so be it.
Hope this helps!
I have a simple problem
I have a java text file which has records like this:
Hamada 115599
Johny 1478523
Bosy 753621
This text file defines the username and password of many accounts in a java program.
I wrote a simple code to edit password of user's account.
System.out.println("Change Account Password");
System.out.printf("Username: ");
String user4 = input.next();
System.out.printf("Password: ");
int pass4 = input.nextInt();
boolean checkaccount = false;
Scanner x = null;
try {
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt"));
while (x.hasNext()) {
String a = x.next();
int b = x.nextInt();
if ((a == null ? user4 == null : a.equals(user4)) && pass4 == b) checkaccount = true;
}
if (checkaccount) {
int newpass = 0;
boolean checked = true;
File f = new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");
File tempFile2 = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt");
BufferedWriter writer2 = new BufferedWriter(new FileWriter(tempFile2));
Scanner sc = new Scanner(f);
Scanner sc2 = new Scanner(System. in );
int foo = Integer.parseInt(user4);
while (sc.hasNext()) {
String currentLine1 = sc.nextLine();
String[] tokens = currentLine1.split(" ");
if (Integer.valueOf(tokens[0]) == foo && checked) {
sc2.nextLine();
System.out.printf("New Password: ");
newpass = sc2.nextInt();
currentLine1 = tokens[0] + " " + newpass;
checked = false;
}
writer2.write(currentLine1 + System.getProperty("line.separator"));
}
writer2.close();
sc.close();
f.delete();
boolean successfull1 = tempFile2.renameTo(f);
if (successfull1 == true) System.out.println("Password changed successfully.");
else System.out.println("Error occurred during changing password.");
} else System.out.println("Wrong username or password... try again !!");
} catch (Exception e) {}
first of all, the program checks if account exists, if it was, then the program allows the user to change password but when i run this code nothing happens and not show me the output statements of "New password: "
what is the wrong with this code ?
If you're getting an exception here - don't just swallow it in your code. Replace the very last line with at least this:
catch (Exception e) {
e.printStackTrace()
}
you'll get a better picture of what is going on.
Does anyone have any ideas how I can complete my code for when a user logs in using their username/password for the first time it notify s them that a new account has been created and then create a text file, with the user/pass in it. Whilest having it proceed to let users with accounts log in as usual.
Here is my code so far. It will read a text file for the username but it will receive a run time error on pass.
import java.util.Scanner;
public class Login{
public static void main (String[] args) {
Scanner scan = new Scanner("Libraries/Documents/userPass.txt");
Scanner keyboard = new Scanner(System.in);
String user = scan.nextLine();
String pass = scan.nextLine();
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if(inpUser.equals(user) && inpPass.equals(pass)){
System.out.print("Welcome");
}
else{
System.out.print("Password or Username is incorrect");
}
}
}
You would better use a XML file to store the usernames and passwords. It's easy to modify and read. And also you can trigger an error messages like User Already Exist if that username contains in XML file. Format will looks like(You can change this format as your choice),
<users>
<user id="1">
<username>User 1</username>
<password>User 1 password</password>
</user>
<user id="2">
<username>User 2</username>
<password>User 2 password</password>
</user>
</users>
and try to encrypt the password for more security. You can check with the username, if signing in user is already exist or not. If not exist, you can write it into the XML and notify a message like A new account has been created.
Here is the tutorial of XML reading and writing.
Read and Write XML in Java
Here is the modification of your code.
import java.io.*;
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
Scanner scan = null;
File file = new File("Libraries/Documents/userPass.txt");
try {
scan = new Scanner(file);
FileWriter fw = new FileWriter(file, true); //the true will append the new data
Scanner keyboard = new Scanner(System.in);
String user = "";
String pass = "";
while (scan.hasNext()) {
user = scan.nextLine();
pass = scan.nextLine();
}
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if (inpUser.equals(user) && inpPass.equals(pass)) {
System.out.print("Welcome");
} else {
System.out.println("Password or Username is incorrect");
fw.write("\n" + inpUser + " " + inpPass);//appends the string to the file
fw.close();
System.out.println("New Account has been created!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help.
Code:
int i = 0;
String fileName = "C:\\Users\\J Urguby\\Documents"
+ "\\NetBeansProjects\\UserPassPageScanner\\src\\userpasspagescanner\\userPass.txt";
File file = new File(fileName);
while (i == 0) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your user name plz:");
String user = keyboard.next();
System.out.println("Enter your password plz");
String pass = keyboard.next();
try (Scanner input = new Scanner(file)) {
while (input.hasNextLine()) {
String[] line = input.nextLine().split(" ");
if (line[0].equals(user) && line[1].equals(pass)) {
System.out.print("Welcome");
i = 1;
}
}
if(i==0) System.out.println("Password or Username is incorrect");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
File Content:
kick 123456
hello 234568
Note: if you need any clarification please let me know
Let's start with, Scanner scan = new Scanner("Libraries/Documents/userPass.txt");, which isn't doing what you think it is. Instead of reading the file userPass.txt, it is using the String value as the contents for the Scanner...
Instead you should be using Scanner(File) instead...
In this case, all you really need to do is check for the existence of the File to determine if it's a new user or not, for example...
File passes = new File("userPass.txt");
try {
String user = null;
String pass = null;
if (passes.exists()) {
try (Scanner scan = new Scanner(passes)) {
user = scan.nextLine();
pass = scan.nextLine();
}
}
if (user == null) {
System.out.println("Welcome new user, please enter the user name and password for your new account...");
} else {
System.out.println("Welcome back user, please enter your user name and password...");
}
Scanner keyboard = new Scanner(System.in);
String inpUser = keyboard.nextLine();
String inpPass = keyboard.nextLine();
if (user == null) {
// Create user account...
} else {
if (inpUser.equals(user) && inpPass.equals(pass)) {
System.out.print("Welcome");
} else {
System.out.print("Password or Username is incorrect");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I created a text field that serves as a data base for Usernames and Passwords.
I tried to make a method that recognizes when there's already an existing username/password which are the same, but it doesn't seem to work.
I think that the problem is in the while loop condition (in exists()), but I can't find out how to fix it.
public class Login{
static Scanner s = new Scanner(System.in);
static Scanner read;
private static Formatter x;
public static void main (String args[]){
try{
x = new Formatter("DataBase.txt");
}catch(Exception e){
e.printStackTrace();
}
try{
read = new Scanner (new File("DataBase.txt"));
}catch(Exception e){
e.printStackTrace();
}
do{
System.out.println("Type LOGIN to login, Type REGISTER to register");
if (s.next().equals("REGISTER")){
System.out.println("Insert username");
String userName = s.next();
while (exists(userName) == true){
System.out.println("ERROR! username already exists");
System.out.println("please selcet a different username");
userName = s.next();
}System.out.println("username is legal");
System.out.println("Insert password");
String passWord = s.next();
while (exists(passWord)){
System.out.println("ERROR! password already exists");
System.out.println("please selcet a different password");
passWord = s.next();
}
x.format("%s %s"+System.lineSeparator(), userName,passWord);
System.out.println("User created");
System.out.println("Type continue to continue, or stop to close");
}
}while (s.next().equals("continue"));
x.close();
}
public static Boolean exists(String str){
while(read.hasNext()){
System.out.println(read.next() +"," + str);
if (read.next().equals(str)) {
return true;
}
}
return false;
}
}
1) First you have to remove the extra call to next() in Syste.out..println statement.
2) After adding data to Formatter you have to call flush()so that data gets written into DataBase.txt file.
3) Your instance variable read is opening the DataBase.txt file at the beginning itself when there is no data in the file. So your exists method will always returns false.
4) The Formatter.format method is not used properly.
Here is the code which works:
public class Login {
static Scanner s = new Scanner(System.in);
static Scanner read;
private static Formatter x;
public static void main(String args[]) {
try {
x = new Formatter("DataBase.txt");
} catch (Exception e) {
e.printStackTrace();
}
do {
System.out.println("Type LOGIN to login, Type REGISTER to register");
if (s.next().equals("REGISTER")) {
System.out.println("Insert username");
String userName = s.next();
while (exists(userName) == true) {
System.out.println("ERROR! username already exists");
System.out.println("please selcet a different username");
userName = s.next();
}
System.out.println("username is legal");
System.out.println("Insert password");
String passWord = s.next();
while (exists(passWord)) {
System.out.println("ERROR! password already exists");
System.out.println("please selcet a different password");
passWord = s.next();
}
x.format("%s%s%s%s", userName,
System.getProperty("line.separator"), passWord,
System.getProperty("line.separator"));
System.out.println("User created");
System.out
.println("Type continue to continue, or stop to close");
x.flush();
}
} while (s.next().equals("continue"));
x.close();
}
public static Boolean exists(String str) {
try {
read = new Scanner(new File("DataBase.txt"));
while (read.hasNext()) {
String data = read.next();
System.out.println(data);
if (data.equals(str)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
read.close();
}
return false;
}
}
as mentioned by Ambrish you can use cache to improve performance instead of reading data from the file every time.
You are reading 2 lines inside your exists() function. So there is 50% chance that you will get -ver result.
Here is the updated code:
public static Boolean exists(String str){
while(read.hasNext()) {
String line = read.next();
System.out.println(line + "," + str);
if (line.equals(str)) {
return true;
}
}
return false;
}
Above solution will in inefficient and you have to read file multiple time. Instead you can create a cache and reuse it.
Like:
static Map<String, String> entires; // Create Cache
public static Boolean existsUser(String str) {
if (entires == null) {
entires = new HashMap<String, String>();
while (read.hasNext()) {
String[] line = read.next().trim().split(" ");
entires.put(line[0], line[1]);
}
}
return entires.containsKey(str);
}
public static Boolean existsPassword(String str, String user) {
if (entires == null) {
entires = new HashMap<String, String>();
while (read.hasNext()) {
String[] line = read.next().trim().split(" ");
entires.put(line[0], line[1]);
}
}
if (entires.containsKey(user)) {
return entires.get(user).equals(str);
}
return false;
}
Of course, you need to keep on updating your cache based on new entry and also you need to refactor your code to use these methods.