so what I am trying to accomplish is check a file to see if a word in the file matches the customers input.
I am attaching the code from when the button is clicked and what its supposed to do. Where its failing, or basically not doing it right, is where its supposed to check to see if it is in the list.
*CODE*
btn1.setOnClickListener(new OnClickListener() { // listen for when i click
public void onClick(View v) {
btn1.setText("yeah");
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
System.out.println("before i read file theirpass =s "+ theirpass);
System.out.println("before i read file checking =s "+ checking);
readFile(); // read the accouts dude
tv1.setText("i pressed the button");// test to make sure button pressing works
System.out.println("after reading. theirpass =s " + theirpass);
System.out.println("after i read file. checking =s "+ checking);
}// end on click
}); //end listener
}// end oncreate
public void readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new. InputStreamReader(getAssets().open("account.txt")));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
mLine = reader.readLine();
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
}// end loop
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
Log.d("Catch buffer","i failed the catch in finally for reading lines");
}
}
}//end buffer reader
Toast.makeText(this,checking,Toast.LENGTH_LONG).show(); //test to get. value of cheking, keeps coming up blank- no text
if (checking == theirpass) {
btn1.setText("its there");//test to see if the if statment works
System.out.println("i just checked if its there");//another test
}
}
}
To help with code
![helping with code again][2]
new Code
if (mLine.equals(theirpass)) { // when an account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking.equals(theirpass); //trying to set vale of checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
} //end buffer reader
value of theirpass
//the value if theirpass is shown below it's in the onClick method
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
Try printing the mLine value right after "mLine = reader.readLine();" to know what you read from the file.
But I guess your biggest problem is the misuse of the "matches" function. Matches uses reg ex (http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) ) .
Instead you should use ".equals" or read this for a good use of string comparison.
You should also change your while loop the this:
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
}// end loop
Because you read a line, go into your while, read a new line and have now skipped the first line of the file.
Related
How can I retrieve the next value from text file when there is a failure in the test case?
Here is my code:
public void openFile(){
try{
x = new Scanner(new File("C:\\Project1\\ids.txt"));
public void readFile(){
}
}catch(Exception e){
System.out.println("not find file");
}
while(x.hasNext()){
String a = x.next();
driver.findElement(By.xpath("//*[#id=\"in_member_id\"]")).sendKeys(a);
}
}
If the value in line number 1 of file ids.text is wrong I want it to put the second value then the third and so on. If it's right I want it to continue to the last of the file.
One strategy you could try if your file isn't unreasonably large is to pre-fetch all the lines and store them in a list. Then loop over and break as the final statement which symbolizes the success that means you can stop trying. That could look something like this:
// Let's just assume the file is always found for example's sake
Scanner in = new Scanner(new File("C:\\Project1\\ids.txt"));
List<String> fileLines = new ArrayList<>();
// Pre fetch all the lines in the file
while (in.hasNextLine()) {
String line = in.nextLine();
if (!line.isEmpty()) {
fileLines.add(line);
}
}
// Try each id until one succeeds and the loop is broken
for (String aLine : fileLines) {
try {
driver.findElement(By.xpath("//*[#id=\"in_member_id\"]")).sendKeys(a);
// Here is where you would check for failures that don't throw an exception, if you need to...
// If this break is reached, then no failures were detected
break;
// If a failure happens that results in an exception
} catch (Exception e) {
System.out.println("An error happened, trying next line");
}
}
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 1 year ago.
Improve this question
I was just experimenting with java (NetBeans) and I though up a quick text based adventure game. I'm trying to get it to check for your username and password in two text files "users.txt" and "passwords.txt" and i was following a guide on Cave of Programming
Here are the imports
import java.io.*;
import javax.swing.JFrame;
This is where the errors are,
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
// file reader for username \\
FileReader fileReader = new FileReader(usernametxt);
// file reader for password \\
FileReader fr = new FileReader(passwordtxt);
// buffered reader for username \\
BufferedReader bufferedReader = new BufferedReader(fileReader);
// buffered reader for password \\
BufferedReader br = new BufferedReader(fr);
// check for if user doesn't equal null \\
while((user = bufferedReader.readLine()) != null){
// if username equals first line of username.txt \\
if (username.getText().equalsIgnoreCase(user)){
// check for if pass doesn't equal null \\
while((pass = br.readLine()) != null){
// if password equals first line of passwords.txt \\
if (password.getPassword().equals(pass)){
// if password = pass than it will exit \\
System.exit(1);
}
// else continue \\
else{
continue;
}
}
}
}
bufferedReader.close();
br.close();
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
Here are the text files
users.txt
matthew
passwords.txt
matt
Full code available here
http://textuploader.com/57urs
Newest Code Here
http://textuploader.com/577qk
feel free to ask me questions here.
Thank you for the help in advance!
Newest Code
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernames = username.getText();
String passwords = password.toString();
boolean signedin = false;
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
FileReader fr1 = new FileReader(usernametxt);
FileReader fr2 = new FileReader(passwordtxt);
BufferedReader br1 = new BufferedReader(fr1);
BufferedReader br2 = new BufferedReader(fr2);
System.out.println("Username: "+br1.readLine());
System.out.println("Password: "+br2.readLine());
// While loops not running (not a if statement error \
while ((user = br1.readLine()) != null){
// checks if username is not equal to usernames.txt \\
if (user.equalsIgnoreCase(usernames)){
System.out.println("while loop running, username (right)");
break;
}
else{
System.out.println("while loop running, username (wrong)");
}
}
br1.close();
while ((pass = br2.readLine())!= null){
if (pass.equalsIgnoreCase(passwords)){
signedin = true;
System.out.println("While loop running, password (right)");
break;
}
else{
System.out.println("While loop running, password (wrong)
}
}
br2.close();
// Commented out the if statements because i dont want to to close while testing \
// if (signedin){
// System.out.println("SIGNEDIN = TRUE");
// new error1().setVisible(true);
// this.dispose();
// }
// if (!signedin){
// System.out.println("SIGNEDIN = FALSE");
// System.exit(1);
// }
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
New Problem
The while loops do not run, this is confirmed when it doesn't print "While loop running, User/Pass", This is not a if/then statement error as I have added the else statement to print if the username is right or wrong. Please help, Thanks Matthew.
If i understood it correctly:
Two files:
users.txt holds the usernames.
passwords.txt holds the passwords.
We want:
Keep reading the user file until the file ends or we've found our user.
Read the corresponding line on the password file and check if the password matches.
Checking the code, while((user = bufferedReader.readLine()) != null) does the first part nicely. We DO want to keep reading the entire file trying to find our user, right?
but the nested while seems a bit fishy. We only need to check a SINGLE password for a given user, right? RIGHT?
Digging a bit deeper into your code, we see:
if (password.getPassword().equals(pass)) {
// if password = pass than it will exit
System.exit(1);
} // plus Lots of code...
Hey! I don't think System.exit does what you're looking for!
System.exit will exit the program, going back to DOS or whatever the cool kids are using these days. The integer it returns is called an error code, and can be used to feed info back to the terminal/shell that started our program.
The keyword you're most likely looking for is break: that will exit a given loop pronto, no questions asked.
Let's do some break/continue mashups! Suppose we "Win at life" if the password is indeed correct:
boolean winAtLife = false;
while((user = bufferedReader.readLine()) != null){
String candidatePassword = br.readLine();
if (candidatePassword == null) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
break;
}
if (!user.equalsIgnoreCase(username.getText())) {
// These are not the droid we're looking for, Better luck next line!
continue;
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves from dreaded NullPointerExceptions!
}
if (!candidatePassword.equals(password.getPassword())) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// since we've found our droid/user/whatever.
// So let's break and save some EC2 Cycles.
break;
}
// If we ever reach here, we got ourselves a winner!
pass = candidatePassword
winAtLife = true;
}
EDIT: Ok... So I've heard that:
The cool kids use Scanner nowadays.
Auto-closing resources is good for our health.
Something about separation of concerns and mixing domain-code with the UI. In code samples. Whatever.
So here we go, take two, now as a method:
public boolean checkCredentials(String username, String password) throws IOException {
// these two are begging to be constants or inlined.
final String usernametxt = "users.txt";
final String passwordtxt = "passwords.txt";
if (username == null || password == null) {
// You probably don't want this in production code.
// Exceptions are your best friends when something unexpected occurs.
return false;
}
try (final Reader fileReader = new FileReader(usernametxt);
final Reader passwordReader = new FileReader(passwordtxt)) {
Scanner userScanner = new Scanner(fileReader);
Scanner passwordScanner = new Scanner(passwordReader);
while(userScanner.hasNext()) {
final String user = userScanner.next();
if (!passwordScanner.hasNext()) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
return false;
}
final String candidatePassword = passwordScanner.next();
if (!user.equalsIgnoreCase(username)) {
// This is not the droid we're looking for
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves
// from dreaded NullPointerExceptions!
continue;
}
if (!candidatePassword.equals(password)) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// So let's return early and save some EC2 Cycles.
return false;
}
// If we ever reach here, we got ourselves a winner!
return true;
}
} // yay for autocloseable
return false;
}
the following method produces an output.
The only problem with this code is that after the end of report, it adds two extra lines to the file, while the need is only of one empty line.
i have tried various combinations but uanble to proceed.
Can anybody help here?
private static void save_player_info(String[][] data, String player) {
player=player.toLowerCase();
try {
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s\n",fields[i],values[i]);
}
printWriter.print("\n");
}
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Instead of unconditionally adding a blank line after the inner for loop, you should conditionally add a blank line before the inner for loop, if not the first time.
Also, you should use %n in printf for the newline, and println() for the blank line. And you should put the close() in a finally block, or use try-with-resources. Showing finally block solution here for Java version independence.
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
try {
boolean first = true;
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
if (first)
first = false;
else
printWriter.println();
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s%n",fields[i],values[i]);
}
}
}
} finally {
printWriter.close();
}
Since you are using new line in
printWriter.printf("%21s : %s\n",fields[i],values[i]);
So you can skip
printWriter.print("\n");
You can wrap an if statement around the line which prints a newline character to check if row is less than data.length. Also, you can use println() instead of print("\n").
for(int row=1;row<data.length;row++){
...
if(row < data.length - 1){
printWriter.println();
}
}
I'm making a game which plays until the user enters quit in the command line.
The user can enter different commands like get and go, with the get command the user can say what to get like, get baseball bat. What I do in my code is split the command.
everything is working fine but I have found a bug which I can't solve. If I enter "get" and press space and then ctrl+z it gets in a while loop which never ends.
It only happens with ctrl+z (1 time with ctrl c but after that 1 time not anymore)
private void run()
{
while (! quitCommand)
{
String input = null;
try
{
input = null;
System.out.println("Input "+ input);
System.out.println("Give a command.");
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
input = is.readLine();
handleCommand(input);
// As long as the command isn’t to quit:
// get the next input line and handle it. (With handleCommand.)
}
catch (Exception e)
{
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
/**
* #param userInput (This is the entire input string from the user.)
*
* (Tell others to) Perform the task which belongs to the given
* command.
*/
private void handleCommand(String userInput)
{
// Split the user input string.
if (userInput != null) // user input can not be empty
{
String[] delenTekst = userInput.split(" ");
// The first word is a command. The rest is extra information
String command = delenTekst[0];
String extra = "";
for (int i = 1; i < delenTekst.length; i ++)
{
if (i == 1)
{
extra = extra + delenTekst[i];
}
else
{
extra = extra +" " + delenTekst[i];
}
}
switch (command)
{
// Check if the command is to travel between rooms. If so, handle
case "go"
:
this.checkRoomTravel(extra);
break;
// If there isn't any room travel, then check all other command
case "get"
:
System.out.println("Looking for " +extra );
this.handleGetCommand(extra);
break;
case "quit"
:
quitCommand = true;
break;
default
:
System.out.println("Command is not known try help for information");
break;
}
}
else
{
userInput = "help";
}
}
I'm new to java so it can be something really simple.
On the top of my script I have a private boolean quitCommand = false; which is to check if the user entered quit.
Ctrl+Z closes the Console and therefore your readLine() returns null as pretended to indicate that end of file was reached. So all you need to do, is to check for null returned by readLine() and handle this as you handle the "quit".
I've changed your code (just to test my thesis) and also stream lined a few things, e.g. you dont need to recreate a BufferedReader every time you read a line.
private boolean quitCommand = false;
private void runIt() {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while(!quitCommand) {
try {
System.out.print("Give a command: ");
input = is.readLine();
// As long as the command isn’t to quit:
if(input == null || "quit".equals(input.trim())) quitCommand = true;
if(quitCommand) break;
// get the next input line and handle it. (With handleCommand.)
String[] words = input.trim().split("\\s+");
// ** This is the original handleCommand line **
System.out.println(input + ":" + Arrays.toString(words));
}
catch (Exception e) {
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
BTW: To split the input into words I'd use the regular expression as shown in my code. This works also if the user enters tabs or multiple spaces.
On DOS/Windows Ctrl+Z means end of input. This causes readLine() to return null no matter how many times you call it. This is likely to cause your code to fail as you don't appear to check for it. I suspect you are getting a NullPointerException which you are pretending didn't happen and trying again, endlessly.
I have a Java Client/Server chat application and after a connection gets established, only about 1 quarter of the data is being received by the recipient. What could the problem be? Here is a print screen of what happens exactly:
Code for reading from socket:
public void somethingElse(){
try {
if(in.readLine() != null){
messageBufferIn = in.readLine();
System.out.println(in.readLine());
chat.append(recipient + ": " + messageBufferIn + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Code for thread that runs above method:
public class chatListener extends Thread{
static main main = new main();
//static Thread mainThread = new Thread(main);
public void run(){
while(main.isConnected == true){
main.somethingElse();
}
}
}
The above thread gets run as soon as a connection gets established
Thanks for any help
Each time you call in.readLine, the scanner moves down to the next line; you can't keep calling it a few times, as it will skip the lines you never used essentially. Try this to replace somethingElse():
public void somethingElse(){
try {
String line;//Added a variable to store the current line to; readLine is
//dynamic, it returns the next line each call, so if we store to a variable,
//we only call it once, and hold that value
if((line = in.readLine()) != null){// (line = in.readLine()) != null is shorthand to store readLine to line, and then check if that returned value is null or not
System.out.println(line);//Print out the line
chat.append(recipient + ": " + line + "\n");//Append it
}
} catch (IOException e) {
e.printStackTrace();
}
}
Before, you were calling in.readLine once to check if it was null, then you saved the next line, then printed the next one. Hence the pattern of (fail success fail | fail success fail etc.) = Only messages 2 + 5 showing up