我如何从数组java中获取值

时间:2015-02-11 23:38:54

标签: java arrays

我目前无法从数组中提取某些值,因为它代表我的数组代码如下:

private List<FootballPlayer> getData() {

    List<FootballPlayer> theData = new ArrayList<FootballPlayer>();

    // create a Scanner and grab the data . . .

    Scanner scanner = null;

    String dataPath = dbLocation + File.separator + "text" + File.separator + "players.db";

    String imagePath = dbLocation + File.separator + "images";

    try {

        scanner = new Scanner(new File(dataPath));

    } catch (FileNotFoundException fnf) { 

        System.out.println(fnf.getMessage());


        System.exit(0);
    }

    // scan player.db file line-by-line

    scanner.useDelimiter("\n");

    while (scanner.hasNext()) {

        String line = scanner.next().trim();

       // trim used to trim for new line

        String[] bits = line.split(":");

        String t = bits[0];                    // title
        String imgFileName = bits[1];          // image file name
        int pa = Integer.parseInt(bits[2]);     // pace
        int sh = Integer.parseInt(bits[3]);     // shooting
        int dr = Integer.parseInt(bits[4]);    // dribbling
        int ph = Integer.parseInt(bits[5]);    // physical

        // create the image

        ImageIcon img = new ImageIcon(imagePath + File.separator + imgFileName);

        // Create the business object

        FootballPlayer player = new FootballPlayer(t, img, pa, sh, dr, ph);

        // add it to the list ... simple as ...

        theData.add(player);
    }

    scanner.close(); 

    return theData;

}

来自players.db文件:

Pique:DFPique.png:66:60:54:76
Ramos:DFRamos.png:79:66:60:82
Maldini:LEGMaldini.png:86:67:56:80
Pele:LEGPele.png:95:94:89:73
DiMaria:MFDiMaria.png:90:87:79:71
Neymar:MFNeymar.png:90:92:80:58
Berahino:STBerahino.png:81:70:69:55
Ronaldo:STRonaldo.png:98:99:99:89

如果选择Ramos,我不确定如何从另一个类中的数组中拉出图像路径(.png)。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

首先:这不是数组,而是List。

第二:你可能需要一个finder方法:

public FootballPlayer findPlayerByName(List<FootballPlayer> players, String name) {
  for (FootballPlayer player: players) {
    if (player.getName().equals(name)) {
      return player;
    }
  }
  return null;
}