簡體   English   中英

否則,如果總是在從文件讀取時執行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM