2016-12-06 38 views
0

[已解決]否則如果總是從文件讀取時執行

通過添加是否已達到語句的標記來修復它。

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是在文件中!到底是怎麼回事?

+0

檢查你嘗試使用字符串上CURR格式,以確保您的字符串是你認爲他們是誰? – Tosh

+0

@Tosh感謝您的快速回復,您是什麼意思的字符串格式? – pmcg521

+1

基本上做了一些快速調試,可以像幾個打印語句一樣簡單,以確保您認爲您使用的字符串與計算機傳遞的字符串相同,如果不是,則使用類似字符串的字符串.format可以讓你的字符串看起來像你期望的那樣 – Tosh

回答

-4

返回值類型爲boolean。嘗試用true/false

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

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

有人可以評論有什麼不對嗎? – roottraveller

相關問題