否则,如果在从文件读取时始终执行

时间:2016-12-06 05:32:27

标签: java file bufferedreader contains

[解决]

通过添加是否已达到该陈述的标记来修正它。

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在文件中!发生了什么事?

1 个答案:

答案 0 :(得分:-4)

返回值的类型为boolean。尝试查看true/false

if(curr.contains(SocSec_input) == true){
}

else if(curr.contains(SocSec_input) == false){
}