Not reading from the file correctly in Java - java

I'm trying to make a game and I am sorting out the account's and im doing it in text files at the moment as im just playing around, the text file for example is,
username
password
and when I run the code below , it runs the else statement every time when the details I enter are correct.
String player;
Scanner loadPlayer = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = loadPlayer.nextLine();
System.out.println();
System.out.print("Enter Passwork: ");
String password = loadPlayer.nextLine();
System.out.println();
try {
File file = new File("/home/kieran/Desktop/project/accounts/"+username+".txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String userData[] = stringBuffer.toString().split("\n");
System.out.println(userData[0]);
System.out.println(userData[1]);
if (userData[0] == username && userData[1] == password){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}
} catch (IOException e) {
e.printStackTrace();
}

if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}

Your string comparison implementation is not OK.
Replace this line
if (userData[0] == username && userData[1] == password){
with this one:
if (userData[0].trim().equals(username.trim()) && userData[1].trim().equals(password.trim())){

try this
if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}

Related

Loop through the file as long as the userinput is same as string in the file

Hey I'm working on a Bank account application and i'm working on the login at the moment. I want the Programm to go through the file and check if there is already a username same as the one the user wants, if there is one it should go back and ask for a new username again. I've tried many different ways but i couldn't find one that works. I hope someone can help me. :-)
String file = "C:\\Users\\dsociety\\IdeaProjects\\bankaccount\\logins.txt";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedReader on = new BufferedReader(new InputStreamReader(System.in));
String username;
String pw;
Boolean exists = false;
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
System.out.println("Please enter a username");
username = in.readLine();
BufferedReader bru = new BufferedReader(new FileReader(file));
String line;
try {
while (exists == true) {
while ((line = bru.readLine()) != null) {
while (scanner.hasNextLine()) {
String[] userAndPw = scanner.nextLine().split(":");
String user = userAndPw[0];
if (user.equals(username)) {
System.out.println("There is already a User with that username, please try a other username");
exists = false;
}
else {
exists = true;
}
}
}
}
bru.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Please enter a password");
pw = on.readLine();
I looked through your code and, as someone else noticed, you can't enter the first while loop because of the exists variable being false. And I think you messed the order of the whiles a little bit.
You definitely don't need a Scanner and a BufferedReader (one of them is enough) for reading the file, just as how you don't need two different BufferedReaders to read from the system input (again, one is sufficient).
I modified your code a little bit and added some comments and I hope it works for you now:
String file = "C:\\logins.txt";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String username;
String pw;
System.out.println("Please enter a username");
BufferedReader bru = new BufferedReader(new FileReader(file));
// we will keep the users here instead of reading the file everytime a username is entered
List<String> users = new ArrayList<>();
Boolean exists = null;
String line;
// populate the existing users list by reading all the lines in the file
while ((line = bru.readLine()) != null) {
users.add(line.split(":")[0]);
}
bru.close();
// we can enter the while loop if we are asking for the username for the first time
// or if the username entered already exists
while (exists == null || exists == true) {
// we read the username from the input
username = in.readLine();
// we suppose it doesn't already exist
exists = false;
// we look at every existing user
for (String user : users) {
/*
* if the names are the same, we don't need to look further, we know the username
* exists and so we will break from the "for" loop and ask for a username once again
* (side note: I used replaceAll in order to remove all invisible unicode characters
* that might make two strings unequal that would otherwise be identical)
*/
if (user.replaceAll("\\P{Print}", "").equals(username.replaceAll("\\P{Print}", ""))) {
System.out.println("There is already a User with that username, please try a other username");
exists = true;
break;
}
}
}
System.out.println("Please enter a password");
pw = in.readLine();
It would be better to divide the job in two parts:
Scan through the file for every username. Put username as key in a map.
Ask for input username, and check if the username is present or not.
if (myMap.containsKey(username) == true) {
// ...
} else {
// Go back to step 2
}
I hope this code will help to solve your issue:
private static boolean userExists(String consoleParam){
String filePath = "C:\\Users\\dsociety\\IdeaProjects\\bankaccount\\logins.txt";
File file = null;
FileReader fr = null;
BufferedReader br = null;
Boolean exists = false;
try{
file = new File (filePath);
fr = new FileReader (file);
br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null){
if(line.split(":")[0].equals(consoleParam)){
exists = true;
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
/* Close opened resources */
try{
if( null != fr ){
fr.close();
}
}catch (Exception e2){
e2.printStackTrace();
}
}
return exists;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
boolean newUser = false;
/* Check if username alredy exists */
while(!newUser){
System.out.println("Please enter a username");
String username = reader.next();
newUser = !userExists(username);
}
/* Close resources */
System.out.println("New username entered!");
reader.close();
}

how to get data from a txt file..split it into two variables and store and modify the this data to the array i used to store the data at the begining [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Im creating a hotel reservation program. I need to store the array which have the details into a txt file and load it afterwards when running the program again..
my data is not storing into the hotel array
public static void Write(String[] hotel){
//storing information of the array into a text file
Scanner sc=new Scanner(System.in);
System.out.println("");
System.out.print("Do you want to write the data to a file(y/n) - ");
String SaveTheFile=sc.nextLine();
if(SaveTheFile.equalsIgnoreCase("y")){
try{
FileWriter file = new FileWriter("Hotel.txt");
PrintWriter pr = new PrintWriter(file);
for(int x =1;x<=10;x++){
pr.println(+x+":"+hotel[x]+":");
}
pr.close();
System.out.println("Write Successful");
System.out.println("");
Menu(hotel);
} catch (IOException e) {
System.err.println("Error!!!");
}
}else if(SaveTheFile.equalsIgnoreCase("n")){
//if the user entered 'n' going back to menu
Menu(hotel);
}else{
//if the user entered any other, displaying an error message
System.err.println("Please Enter 'y' or 'n' !!!");
Write(hotel);
}
}
public static String[] Load(String[] hotel){
String line = null;
String numSt,name;
int num;
System.out.println("");
Scanner sc = new Scanner(System.in);
try {
FileReader fr = new FileReader("Hotel.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
String[] token = line.split(":");
numSt = token[0];
name = token[1];
num = Integer.parseInt(numSt);
hotel[num]=name;
}
br.close();
} catch (IOException e) {
System.out.println("file not found");
}
catch (NullPointerException f) {
System.out.println("Null pointer here...");
}
return hotel;
}
I found out the answer......
String line = "";
int counter = 0;
while ((line = br.readLine()) != null) {
numSt = line.split(":")[0];
name = line.split(":")[1];
counter = Integer.parseInt(numSt);
hotel[counter]=name;
counter++;
Thank u for spending your valuable time for helping me to sort this out :)
String line = null;
You never give this variable an actual value other than null so it will be null when you first use it. If this is not the error please provide the log.

Java reading a string from a text(txt) file

Rod
Rae
Bryan
Shiroe
Ric
Kirito
Asuna
Elsa
Akutabe
Shino
I have that list saved in a text file. If I were to enter Rod, it should say "Exists" and if I enter a name that is not on the list, it should say "Does not exist." But what is happening on my code is that it reads the file per line and prints "Does not exist" if it does not match the string line.
So if I were to enter a name that does not exist in the txt file, it would print 10 "Does not exist" lines.
This is my code below:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
break;
} else {
out.println("Does not exist");
}
}
br.close();
An example of a what would be output is:
name = Kirito
Does not exist
Does not exist
Does not exist
Does not exist
Exists
Why does my program print so many Does not exist before finding the exact match?
Use a boolean to remember whether you have found a match, and display "Does not exist" only after checking every item and only if you have not found a match.
You were almost there. You are just preemptively printing the error message. I would have also used equals instead of contains and pre-loaded the entire file into. HashSet if multiple queries need to be answered
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
found = true;
break;
}
}
if (!found) {
out.println("Does not exist");
}
br.close();
You're breaking the loop if the name exists, so you should only print the "not exists" message if the loop doesn't break:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean nameFound = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
nameFound = true;
break;
}
if (!nameFound) {
out.println("Does not exist");
}
br.close();
PrintStream out = System.out;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
out.print("Enter name: ");
String name = in.readLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean ifexist = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
ifexist = true;
break;
}
}
if (ifexist) {
out.print("Exist");
} else {
out.println("Does not exist");
}
br.close();
Add a boolean var default false, when exist set it to true and break. Than output.

Why does this `do-while/for loop` never end if you give an invalid input?

I have a for loop nested inside a do-while loop which is to read through a text file and look for the given input. I have noticed that it works perfectly fine if you give an input which exists in the file, however can someone help me understand why the program never exits the loop if you give an input which does not exist in the text file, even though it should exit when the variable with the text from the file becomes null. I have posted all relevant code from the method where the for loop is being executed, including the part where it gains the user input; just to be clear, there are no errors given when compiling or running the program.
FileReader fileReader = new FileReader("VirtualATM.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.print("Enter your pin: ");
char [] EnterPin = {0, 0, 0 ,0};
try{
EnterPin = System.console().readPassword();
}catch(InputMismatchException e){
e.printStackTrace();
System.out.println(e.getMessage());
//System.out.println(e.getLocalizedMessage());
}
boolean pinTrue = false;
String LineFromFile = null;
LineFromFile = bufferedReader.readLine();
String [] PinSearch = LineFromFile.split("\\s+");
String UserPin = java.util.Arrays.toString(EnterPin);
String PinMod = UserPin.replaceAll("\\[", "");
String PinMod2 = PinMod.replaceAll("\\,", "");
String PinMod3 = PinMod2.replaceAll("\\s+", "");
String PinToWrite = PinMod3.replaceAll("\\]", "");
do{
for(int search = 0; search < PinSearch.length; search++){
String SearchForPin = PinSearch[search];
if(SearchForPin.matches(PinToWrite)){
pinTrue = true;
System.out.println("Success!");
}
else if(search => PinSearch.length){
System.out.println("Error! Invalid pin.");
}
}
LineFromFile = bufferedReader.readLine();
}while(pinTrue == false && line != null);
}catch(IOException e){
e.printStackTrace();
System.out.println(e.getLocalizedMessage());
}
You need to move the line processing to be inside the loop, after each line you read. Otherwise, you only process the first line you read before the loop.
do{
for(int search = 0; search < PinSearch.length; search++){
String SearchForPin = PinSearch[search];
if(SearchForPin.matches(PinToWrite)){
pinTrue = true;
System.out.println("Success!");
}
else if(search => PinSearch.length){
System.out.println("Error! Invalid pin.");
}
}
LineFromFile = bufferedReader.readLine();
if (LineFromFile != null) {
PinSearch = LineFromFile.split("\\s+");
UserPin = java.util.Arrays.toString(EnterPin);
PinMod = UserPin.replaceAll("\\[", "");
PinMod2 = PinMod.replaceAll("\\,", "");
PinMod3 = PinMod2.replaceAll("\\s+", "");
PinToWrite = PinMod3.replaceAll("\\]", "");
}
} while(pinTrue == false && LineFromFile != null);
Because you're testing line, but reading into LineFromFile.
Change this
}while(pinTrue == false && line != null);
to something like
}while(!pinTrue && LineFromFile != null);
And, as Eran notes here, your line processing logic should be in the body of the do, so
do{
String LineFromFile = bufferedReader.readLine();
String [] PinSearch = LineFromFile.split("\\s+");
String UserPin = java.util.Arrays.toString(EnterPin);
String PinMod = UserPin.replaceAll("\\[", "");
String PinMod2 = PinMod.replaceAll("\\,", "");
String PinMod3 = PinMod2.replaceAll("\\s+", "");
String PinToWrite = PinMod3.replaceAll("\\]", "");

Replace a character in java?

public void sendData(){
try {
URL data = new URL("http://mywebsite.net/isvalid.php?username=" + usernameField.getText() + "&password=" + passwordField.getText());
BufferedReader in = new BufferedReader(
new InputStreamReader(data.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
if(inputLine.length() > 0)
inputString = inputLine;
in.close();
if(!inputString.equals("Incorrect password.")){
System.out.println("Correct password");
run();
dispose();
} else
if(usernameField.getText().length() > 0 && passwordField.getText().length() > 0) {
invalidUP();
System.out.println("Invalid username or password.");
} else
if(usernameField.getText().length() < 1 || (passwordField.getText().length() < 1)) {
System.out.println("No password or username entered.");
upLength();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How would I check if usernameField or passwordField would have a space in it? And if it has, replace it with "_".
Also, if you think this method is wrong to send data or it can be done easier/quicker, please elaborate.
Using String#replaceAll():
String uname ="abc xyz";
uname = uname.replaceAll("\\s+", "_");
Look at String.replace:
passwordField = passwordField.replace(' ', '_');
java.lang.String has a nice method called replaceAll.
If there is only space in your String then try this:
username = username.replace(" " , "_");
Otherwise if there are whitespace in your username then try this:
username = username.replaceAll("\\s+" , "_");

Categories

Resources