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.
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 want to ask about my programming code. There seems to be a mistake. Please check my code below, it didn't turn out to what I had expected. The problem is, I'm imputing the right username but it repeats again. I'd really appreciate all your answers
static Scanner scan;
static ArrayList<String> EmailList;
static ArrayList<String> FullNameList;
static ArrayList<String> UsernameList;
static ArrayList<String> PasswordList;
public static void clear(){
for(int i =0; i < 24; i++){
System.out.println();
}
}
public static boolean ouragreement (String agreement){
if(agreement.isEmpty()){
return false;
}
else if(agreement.equalsIgnoreCase("N") || agreement.equalsIgnoreCase ("No")){
return false;
}
return true;
}
public static boolean validateusername (String username, ArrayList<String>UsernameList){
if(username.isEmpty()){
System.out.println("Username cannot be empty");
return false;
}
else if(!username.equals(UsernameList.size())){
System.out.println("Please input again your username");
return false;
}
return true;
}//validateusername
public static boolean validatepassword(String password, ArrayList<String>PasswordList){
if(password.isEmpty()){
System.out.println("Password cannot be empty");
return false;
}
else if(!password.equals(PasswordList.size())){
System.out.println("Please input again your password");
return false;
}
return true;
}//validatepassword
public static void case1(){
String email, fullname, username, password, agreement;
System.out.print("Input your email : ");
email = scan.nextLine();
System.out.print("Input your Full name : ");
fullname = scan.nextLine();
System.out.print("Input your username : ");
username = scan.nextLine();
System.out.print("Input your password : ");
password = scan.nextLine();
EmailList.add(email);
FullNameList.add(fullname);
UsernameList.add(username);
PasswordList.add(password);
do{
System.out.print("If you say Yes[Y], you agreed to our Terms & Privacy Policy [Y/N] : ");
agreement = scan.nextLine();
}while(!ouragreement(agreement));
clear();
System.out.println("Sign Up Success!");
System.out.println();
}//case1
public static void case2(){
String username,password;
do{
System.out.print("Username : ");
username = scan.nextLine();
}while(!validateusername(username,UsernameList));
do{
System.out.print("Password : ");
password = scan.nextLine();
}while(!validatepassword(password,PasswordList));
System.out.println("Welcome");
}//case2
public static void inisialisasi (){
scan = new Scanner (System.in);
EmailList = new ArrayList<>();
FullNameList = new ArrayList <>();
UsernameList = new ArrayList<>();
PasswordList = new ArrayList<>();
}//inisialisasi
public static void main (String [] args){
inisialisasi();
int choose;
do{
System.out.println("\tKOSTFINDER APPLICATION");
System.out.println("\t======================\n");
System.out.println("Welcome to KostFinder Application, please choose option below");
System.out.println("1. Sign up");
System.out.println("2. Login");
System.out.print("Choose :");
choose = scan.nextInt(); scan.nextLine();
switch(choose){
case 1 :
case1();
break;
case 2 :
case2();
break;
}
}while(choose != 101);
}//main
}//public class
The problem lies in these two methods:
public static boolean validateusername (String username, ArrayList<String>UsernameList){
if(username.isEmpty()){
System.out.println("Username cannot be empty");
return false;
}
else if(!username.equals(UsernameList.size())){
System.out.println("Please input again your username");
return false;
}
return true;
}//validateusername
public static boolean validatepassword(String password, ArrayList<String>PasswordList){
if(password.isEmpty()){
System.out.println("Password cannot be empty");
return false;
}
else if(!password.equals(PasswordList.size())){
System.out.println("Please input again your password");
return false;
}
return true;
}//validatepassword
The condition !password.equals(PasswordList.size()) does not make much sense. You should find the index of the entered user name in the user names list, find the password at that index in the passwords list and check whether the entered password is equal to that password. This means that you should really create a single method that validates both password and user name. This is because passwords and user names are highly related. You can't know whether a password is correct without knowing the user name.
Also, you did not check whether the new user name added to the list is duplicate or not. Not to mention that you allowed empty user names and passwords to be entered in the sign up process while not allowing them when logging in. But these are smaller problems relative to the problem mentioned in the previous paragraph.
Your validateUsernameAndPassword method should look like this:
public static boolean validateUsernameAndPassword(String username, String password) {
int index = UsernameList.indexOf(username);
if (index == -1) {
System.out.println("The user name does not exist");
return false;
}
String correctPassword = PasswordList.get(index);
if (correctPassword.equals(password)) {
return true;
} else {
System.out.println("Please input again your password");
return false;
}
}
Note: This way of storing passwords is highly insecure. I understand this is not production code, but never do something like this in production code. At least you should do a hashing algorithm.
I haven't been able to find an answer to this question. It is a proof of concept bank login page.
The purpose is that if the input matches an entry in the array, you are allowed in.
I have tried object.equals and the like but get I cannot compile correctly.
Here is my code:
import java.util.Scanner;
public class JBLogin {
public static void main(String[] args);
{
String username
Scanner login = new Scanner(System.in);
String [] database;
database = new String[2];
database[0] = "placeholderone";
database[1] = "placeholdertwo";
System.out.println(" Welcome To JavaBank!");
System.out.println("Please Enter Your Username:");
username = login.next();
System.out.println("Welcome Back, " + username);
if (username.object.equals(database))
{
System.out.println("_____________");
}
else
{
System.out.println("Username Not Found.");
}
}
}
You need to compare every element in the array database with username. You can do that using a loop.
Also, to call the Object.equals method on username, you just say: username.equals(...). You shouldn't put .object in between.
boolean found = false;
for (int d = 0; d < database.length; d++) {
if (database[d].equals(username)) {
found = true;
}
}
if (found) {
System.out.println("_____________");
} else {
System.out.println("Username Not Found.");
}
And as others have mentioned, you should also remove the semicolon from the end of the method declaration line:
public static void main(String [] args);
And you should put a semicolon behind the line that declares the String username:
String username;
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();
}