程序是从包含玩家号码和统计数据的文本文件中获取输入。如果某个球员已经在列表中,我想更新该球员的统计数据。我在确定玩家是否已经在列表中的方法上遇到了问题。无论如何,当前方法都会打印所有玩家。问题是否出在我的主类或方法中的代码上?public class Baseball8{ public static void main(String[] args) throws FileNotFoundException { Scanner fin = new Scanner(new FileReader("baseball.txt")); final int LIST_LENGTH = 20; int number = 0, // number, hits, walks, outs hits = 0, walks = 0, outs = 0, players = 0, index = 0, teamSize = 0; playerIndex = 0; System.out.println("This program tracks a baseball player's number " + "and their\number of walks, runs and outs for " + "each game in a season.\n"); Player team[] = new Player[LIST_LENGTH]; int i; for(i = 0; i < LIST_LENGTH; i++) team[i] = new Player();while (fin.hasNext()) { number = fin.nextInt(); hits = fin.nextInt(); walks = fin.nextInt(); outs = fin.nextInt(); System.out.println(number + " " + hits + " " + walks + " " + outs + " "); playerIndex = findPlayerIndex(team,teamSize,number); if(playerIndex == -1) { team[teamSize].setNumber(number); team[teamSize].setHits(hits); team[teamSize].setWalks(walks); team[teamSize].setOuts(outs); teamSize++; } else { team[index].setHits(hits + team[index].getHits()); team[index].setWalks(walks + team[index].getWalks()); team[index].setOuts(outs + team[index].getOuts()); } }displayArray(team, teamSize);fin.close();}.public static int findPlayerIndex(Player p[], int n, int number){ int i; for(i = 0; i < n; i++); { if(p[i].getNumber() == number) return i; else return -1; }} **Current output:**//player hits, walks, outs are added to array[0] Player Hits Walks Outs------ ---- ----- ---- 1 5 10 18 <19 0 5 1 2 0 0 618 4 2 0 4 1 2 312 2 2 2 7 0 0 3 8 1 4 110 2 2 2 3 2 1 311 6 0 017 4 2 0 9 3 2 1Desired output://stats added to array[i]Player Hits Walks Outs------ ---- ----- ---- 1 2 2 219 0 5 7 < 2 0 5 718 4 2 0 4 3 3 6 <12 2 2 2 7 0 0 6 < 8 1 4 110 2 2 2 3 3 3 6 <11 6 0 017 4 2 0 9 3 2 1 最佳答案 你的函数 findPlayerIndex 有两个问题 删除; for so 循环后可以工作: for(i = 0; i ; 循环结束后返回-1, int i 可以在循环命令中声明。像这样:for (int i = 0; i < n; i++) { if(p[i].getNumber() == number) return i;}return -1; 玩得开心!关于java - 更新数组列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44272691/
10-15 11:49