Java Text file logon - java

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();
}

Related

How to find a String in a .txt file and then read the data after it

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

Java delimiter on a text file

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();

Making login using arraylist from file java code?

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!

Creating registration program in java?

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();

Reading a file with scanner

EDIT: I ADDED A NEW PART to catch fileexception error
This is a pincheck program. I'm supposed to create a txt file with the following lines:
peter, 1212
john, 1234
mary, 0000
I then have to write a java program to prompt user for the file path of the txt file then key in their name and pin number. I'm able to compile my code but I don’t get the expected result when I type in the correct name and pin.
import java.util.*;
import java.io.*;
public class PINCheck {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter file path: ");
String filepath = s.nextLine();
File passwordFile = new File(filepath);
System.out.print("Enter name: ");
String name = s.nextLine();
System.out.print("Enter password: ");
String password = s.nextLine();
try {
Scanner sc = new Scanner(passwordFile);
while (sc.hasNext()) {
if (password.matches(".*[a-zA-Z]+.*")) {
System.out.println("You have entered a non-numerical PIN!");
} else if (sc.hasNext(name) && sc.hasNext(password)) {
System.out.println("You have logged in successfully.");
}else {
System.out.println("Login Failed.");
}
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
This line : Scanner sc = new Scanner("passwordFile"); implies that Scanner will scan from the String specified in the constructor and not the actual file.
Use Scanner sc = new Scanner(passwordFile); instead.
A similar mistake for File passwordFile = new File("filepath");.
Use it like File passwordFile = new File(filepath);
In both cases, pass the variable, not the string.

Categories

Resources