2015-09-17 81 views
1

我正在爲庫存目的構建標籤閱讀器。使用for循環遍歷標籤來計算/總計id。我在返回行中出現錯誤「tagsFound無法解析爲變量」。如何在for循環中使用變量,然後在循環外部訪問它?從if中返回數組,for語句

public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{ 
    int coneCount = 0; 
    int drumCount = 0; 

    // Open a connection to the reader 
     reader.open(); 
    // Ask the reader to read tags and print them 
     Tag tagList[] = reader.getTagList(); 
     if (tagList == null) { 
     System.out.println("No Tags Found"); 
     } else { 
     System.out.println("Tag(s) found: " + tagList.length); 
     for (int i=0; i<tagList.length; i++) { 
      Tag tag = tagList[i]; 
      System.out.println("ID:" + tag.getTagID() + 
          ", Discovered:" + tag.getDiscoverTime() + 
          ", Last Seen:" + tag.getRenewTime() + 
          ", Antenna:" + tag.getAntenna() + 
          ", Reads:" + tag.getRenewCount() 
          ); 
     //tagFound[i]= "" + tag.getTagID(); 
      String phrase = tag.getTagID(); 
      tagFound[i] = phrase; 
      String delims = "[ ]+"; 
      String[] tokens = phrase.split(delims); 
      if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;} 
      if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;} 
      String[] tagsFound; 
     tagsFound[i] = tag.getTagID(); 
     } 
     System.out.println("Cones= " + coneCount); 
     System.out.println("Drums= " + drumCount); 

     // Close the connection 
     reader.close(); 
     return tagsFound; 
    } 
} 

回答

1
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{ 
int coneCount = 0; 
int drumCount = 0; 

// Open a connection to the reader 
    reader.open(); 
// Ask the reader to read tags and print them 
    Tag tagList[] = reader.getTagList(); 
    if (tagList == null) { 
    System.out.println("No Tags Found"); 
    } else { 
    System.out.println("Tag(s) found: " + tagList.length); 
    String[] tagsFound = new String[tagList.length]; 
    for (int i=0; i<tagList.length; i++) { 
     tagsFound = ""; 
     Tag tag = tagList[i]; 
     System.out.println("ID:" + tag.getTagID() + 
         ", Discovered:" + tag.getDiscoverTime() + 
         ", Last Seen:" + tag.getRenewTime() + 
         ", Antenna:" + tag.getAntenna() + 
         ", Reads:" + tag.getRenewCount() 
         ); 
    //tagFound[i]= "" + tag.getTagID(); 
     String phrase = tag.getTagID(); 
     tagFound[i] = phrase; 
     String delims = "[ ]+"; 
     String[] tokens = phrase.split(delims); 
     if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;} 
     if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;} 
    tagsFound[i] = tag.getTagID(); 
    } 
    System.out.println("Cones= " + coneCount); 
    System.out.println("Drums= " + drumCount); 

    // Close the connection 
    reader.close(); 
    return tagsFound; 
} 
} 

返回的數組將具有在其中標籤不滿足標準的位置空字符串。

+0

感謝您的快速回復,我現在收到一個錯誤「類型不匹配:無法從字符串轉換爲字符串[]」爲行tagsFound =「」; –

+0

數組類型必須是從getTagID方法返回的標記類型 – hasan83