从数组列表中获取特定值

时间:2017-12-02 08:55:21

标签: java arraylist

        while (fileScan.hasNextLine())
        {
            line = fileScan.nextLine();
            lineScan = new Scanner(line);
            int playerType = Integer.parseInt(lineScan.next());
            if (playerType == 0)
            {
                availPlayers.add(player = new Player(playerType, Integer.parseInt(lineScan.next())));
            }
            else if (playerType == 1)
            {
                availPlayers.add(vip = new VIP(playerType, Integer.parseInt(lineScan.next()), Integer.parseInt(lineScan.next()), lineScan.next(), lineScan.next()));
            }
            else if (playerType == 2)
            {
                availPlayers.add(superVip = new SuperVIP(playerType, Integer.parseInt(lineScan.next()), Integer.parseInt(lineScan.next()), lineScan.next(), lineScan.next()));
            }
        }
players.txt 
0 100
1 500 1234 Jane Smith
1 300 3455 John Smith
0 500
2 1000 9867 Hot Shot
0 200
0 300
2 2000 5555 Charles B 

有没有办法可以提取每个单独的值并将它们设置为变量?

[0 100, 1 500 1234 Jane Smith, 1 300 3455 John Smith, 0 500, 2 1000 9867 Hot Shot, 0 200, 0 300, 2 2000 5555 Charles B]

例如,我想将1,500,1234分别设置为int变量,将John和Smith分别设置为字符串变量。

2 个答案:

答案 0 :(得分:0)

我不确定这是否是你想要的,因为问题不清楚。但是从我最好的猜测来看,String.split()就是你所需要的。

实施例

String input = "1 500 1234 Jane Smith";

List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();

for (String s : input.split(" ")) {
    // Split the string at spaces.
    try {
        // Try parsing as an integer.
        integers.add(Integer.parseInt(s));
    } catch (NumberFormatException e) {
        // NumberFormatException will be thrown if the string cannot be parsed as an integer, 
        // in this case we continue to process it as a string.
        strings.add(s);
    }
}

System.out.println(strings); // ["Jane", "Smith"]
System.out.println(integers); // ["1", "500", "1234"]

答案 1 :(得分:0)

是的,您在Player VIP中持有SuperVIPavailPlayerslist个对象。我假设他们实现相同的界面,让我们说Human。所以你可以做的是,你可以遍历循环中的availPlayers和列表中的所有项目,你可以得到playerType并根据玩家类型你可以得到你需要的所有值通过getter方法。像下面这样的东西。此处getIntValuegetStrValue只是示例,您需要在基类中使用getter方法更改这些示例。

for (int i = 0; i < availPlayers.size(); i++)
  int playerType = h.getPlayerType();
  if (playerType == 0) {
    int i1 = availPlayers.get(i).getIntValue();
  }
  else if (playerType == 1) {
    String strValue = availPlayers.get(i).getStrValue();
  }
  else if (playerType == 2) {
    String strValue = availPlayers.get(i).getStrValue();
  }
}