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.
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 trying to read a txt file with this format (heading not included):
firstname lastname username password
John Doe $1234567 $123
Eden Hask $1234576 $12345
The latest login (Eden) would always work but not the one prior(John).
For some reason, the delimiter would include all details until the next $.
How should I get my delimiter to stop after the password.
The user name is_1234567 and the password is_123
Eden Hask!
The user name is_1234576 and the password is_12345!
Here is the entire code.
public void login() throws FileNotFoundException{
File file = new File("file.txt");
Scanner read = new Scanner(file);
found = false;
read.useDelimiter("(\s*\\$)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String user = read.next();
String pass = read.next();
System.out.println("The user name is_" + user + " and the password is_" + pass + "!\n");
if(user.trim().equals(username) && pass.trim().equals(passwordField)){
boolean found = true;
break;
}
}
if(found){
return true;
}
else {
return false;
}
read.close();
}catch(Exception e){
throw e;
}
};
I would do it completely different:
boolean found;
public void login() throws FileNotFoundException {
File file = new File("file.txt");
Scanner read = new Scanner(file);
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String password = keyboard.nextLine();
// Skip the first line
read.nextLine();
while (read.hasNextLine()) {
String line = read.nextLine();
//split current line with spaces into an array
String[] lineArray = line.split("\\s+");
String user = lineArray[1];
String pass = lineArray[4];
System.out.println("The user name is " + user + " and the password is " + pass + "!\n");
if (user.equals(username) && pass.equals(password)) {
found = true;
break;
}
}
read.close();
keyboard.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From what you have described it looks like you also want to break your string when a line ends. To do this add a carriage return as one of delimiting cases in the following manner-
read.useDelimiter("\n|(\s*\\$)")
this should prevent all the previous 'password' strings from including details from the next line
In addition to the line break inclusion in the delimiter, you may want to read the name of the user to keep the userid/password reads in sync:
read.useDelimiter("(\\s*\\$)|(\\R)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String name = read.next();
String user = read.next();
String pass = read.next();
I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help
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();
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();
}