如何多次修复阵列打印

时间:2017-03-21 03:50:31

标签: java for-loop

当我运行此方法并在countLabel上设置文本时,它会打印26次。任何人都可以解释为什么会发生这种情况如何解决这个问题

void updateCounts() {
    int[] letterCounts = new int[26];
    for (int i = 0; i < 26; i++) {
        letterCounts[i] = 0;
    }

    String s = encrypted.getText();
    s = s.toUpperCase();

    for (int i = 0; i < s.length(); i++) {
        int j = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(s.charAt(i));
        if (j >= 0) {
            letterCounts[j] += 1;
        }
    }

    String countString = "";
    for (int i = 0; i < 26; i++) {
        String n = Arrays.toString(letterCounts);

        if (n.equals("0")) {
            countString = countString + "   ";
        } else if (n.length() == 1) {
            countString = countString + " " + n + " ";
        } else {
            countString = countString + n + " ";
        }
    }

    String noCommas = countString.replace(',', ' ');
    countLabel.setText(noCommas.replace('0', ' '));
    System.out.println(noCommas.replace(',', ' '));
}

1 个答案:

答案 0 :(得分:0)

Hi ExtremelyAverageProgrammer,

在您提供的方法中,输出仅在结尾处发生一次:

System.out.println(noCommas.replace(',', ' '));

这意味着在您的main方法中,您正在调用方法&#34; updateCounts()&#34; 26次,这可以解释不规则的输出。

希望这有帮助!