数组存储了太多的值

时间:2018-07-12 22:34:05

标签: java arrays for-loop

该程序用于比较先前的输入和当前的输入。如果尚未输入输入,则该输入将存储在团队的下一个索引中并与具有相同值的索引一起存储。如果输入已经输入,则该值将递增 注意:数组“分数”已初始化为int。数组“ team”被初始化为String。 W

for (j = 0; !input.equals("x"); j++ )  // problem with j making too many on the list
    { // moves onto a new 
        System.out.println("Which team just won? (x to exit)"); 
        input = scnr.nextLine();
        for (i = 0; i < team.length && !input.equals("x"); i++) 
        { // compares input against previous inputs
            if (team[i].equals(input)) 
            { // comparison issue FIXME
                score[i]++; 
                break;
            }
            else if (!team[i].equals(input) && score[j] == 0) 
            {
                team[j] = input;
                score[j] = 1;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

这是您可以使用的另一种方法:

import java.util.Scanner;

class Scratch {
    public static final int MAX_SIZE = 1000;

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        String input;
        String[] team = new String[MAX_SIZE];
        int[] score = new int[MAX_SIZE];
        int currentTeamCount = 0;
        boolean teamAlreadyExists = false;

        System.out.println("Which team just won? (x to exit)");
        input = scnr.nextLine();
        while (!input.equalsIgnoreCase("x")) {
            teamAlreadyExists = false;

            for (int i = 0; i < currentTeamCount; i++) {
                if (input.equals(team[i])) {
                    score[i]++;
                    teamAlreadyExists = true;
                    break;
                }
            }

            if (!teamAlreadyExists) {
                team[currentTeamCount] = input;
                score[currentTeamCount] = 1;
                currentTeamCount++;
            }

            System.out.println("Which team just won? (x to exit)");
            input = scnr.nextLine();
        }

        for (int i = 0 ; i < currentTeamCount; i++) {
            System.out.println(team[i] + " " + score[i]);
        }
    }
}

样本输入:

Which team just won? (x to exit)
A
Which team just won? (x to exit)
B
Which team just won? (x to exit)
C
Which team just won? (x to exit)
D
Which team just won? (x to exit)
D
Which team just won? (x to exit)
D
Which team just won? (x to exit)
C
Which team just won? (x to exit)
B
Which team just won? (x to exit)
E
Which team just won? (x to exit)
F
Which team just won? (x to exit)
F
Which team just won? (x to exit)
x

输出:

A 1
B 2
C 2
D 3
E 1
F 2

希望它会有所帮助:)