2016-12-06 36 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