[SOLVED]
Fixed it by adding a marker for whether or not the statement was reached.
if(contains) // condition reached. marker "found" is 1.
found = 1;
else if(found != 1){ // If found is not 1, not found. break.
System.out.println("Not found"); break;
Writing a program that involves reading an example SSN from a file. I'm trying to account for invalid input (that is, the string is not inside the file). However, the statements do not execute how I want them to. (Ignore everything but how my if statements are structured).
public static void getNameNum(String SocSec_input){
try{
reader1 = new BufferedReader(new FileReader("src\\DEPARTMENT.txt"));
reader2 = new BufferedReader(new FileReader("src\\EMPLOYEE.txt"));
/**
* reads from employee text file
*/
while((curr = reader2.readLine()) != null){
/**
* checks which lines contain user input and split the name from the code into storage
*/
if(curr.contains(SocSec_input)){
String[] parts = curr.split(",");
String FNAME = parts[0];
String LNAME = parts[1];
String SSN = parts[2];
String DNO = parts[9];
if(SSN.equals(SocSec_input)){
while((curr = reader1.readLine()) != null){
/**
* searches the file for the user input
*/
if(curr.contains(DNO)){
/**
* splits the line containing user input at each comma and store the values
*/
String[] parts2 = curr.split(",");
String DNAME = parts2[0];
String DNUMBER = parts2[1];
if(DNUMBER.equals(DNO))
System.out.println(FNAME + " " + LNAME + " works in department " + DNO + ", " + DNAME);
}
}
}
}
// ALWAYS EXECUTING STATEMENT HERE*****************
else if(!(curr.contains(SocSec_input))){
System.out.println("Invalid SSN entered. We could not find
that SSN in our database.");
break;
}
}
}
catch (IOException e){
e.printStackTrace();
}
}
Output:
Please enter the employee's SSN: 123
Invalid SSN entered. We could not find that SSN in our database.
Please enter the employee's SSN: 888665555
Invalid SSN entered. We could not find that SSN in our database.
--------------------
But 888665555 is in the file! What is going on?
The return value is of type boolean
. try to check with true/false
if(curr.contains(SocSec_input) == true){
}
and
else if(curr.contains(SocSec_input) == false){
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.