![](/img/trans.png)
[英]BufferedReader input while reading from file always null in while loop
[英]Else if always executing while reading from file
[解决了]
通过添加是否达到该语句的标记来修复此问题。
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;
编写涉及从文件中读取示例SSN的程序。 我正在尝试解释无效输入(也就是说,字符串不在文件内)。 但是,这些语句不执行我希望它们执行的方式。 (忽略所有内容,但if语句的结构如何)。
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();
}
}
输出:
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.
--------------------
但是文件中有888665555! 到底是怎么回事?
返回值是boolean
类型。 尝试检查是否true/false
if(curr.contains(SocSec_input) == true){
}
和
else if(curr.contains(SocSec_input) == false){
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.