如何在 Java 中通过不使用 Stream 在几行中将 newPassArray[i] 打印为字符串?

How can I print out newPassArray[i] as String in few lines in Java by NOT USING Stream?

提问人:Cocopapoo 提问时间:8/30/2023 更新时间:9/8/2023 访问量:28

问:

亲爱的能解决这个问题的人,我真的很感谢你的好意! 我是编程新手(不到1年)

我尝试使用 toSting() 但它也会打印出空索引,我怎样才能摆脱那些空索引,只显示我想要的分数,而不是使用 Stream 这是我的代码:

public class ArrayStream4 {
    public static void main(String[] args) {
        int [] scores = {100, 50, 40, 70, 90};
        // Question: Please calculate the following: How many individuals have achieved a "passing" grade(i>=60) and print out the grade? The total score? The average? The highest score? The lowest score?
        
        int total = 0; 
        int max = scores[0];
        int min = scores[0];
        int passCount = 0;
        int [] newPassArray = new int[scores.length];
        int passingIndex = 0;


        for(int score : scores){
            total += score;
            
            if(score > max){
                max = score;
            }
            if (score < min){
                min = score;
            }
            if(score >= 60){
                passCount ++;
                newPassArray[passingIndex] = score;
                passingIndex ++;
            }
        }
            for (int i = 0; i < passingIndex; i++) {
                System.out.print(newPassArray[i]);
                
            }
            System.out.println();
            System.out.println("PASS grade: " + Arrays.toString(newPassArray));
            System.out.printf("Total grade: %d\n", total);
            System.out.printf("Min grade: %d\n", min);
            System.out.printf("Max grade: %d\n", max);
            System.out.printf("PASSCount: %d\n", passCount);

    }
}

Java 数组 tostring

评论

0赞 Cocopapoo 8/30/2023
->[100, 70, 90, 0, 0] -------------------------我想要: ->[100, 70, 90]

答:

1赞 Cocopapoo 8/30/2023 #1

问题解决了!!

public class ArrayStream4 {
    public static void main(String[] args) {
        int[] scores = {100, 50, 40, 70, 90};
        int total = 0;
        int max = scores[0];
        int min = scores[0];
        int passCount = 0;
        List<Integer> newPassList = new ArrayList<>();

        for (int score : scores) {
            total += score;

            if (score > max) {
                max = score;
            }
            if (score < min) {
                min = score;
            }
            if (score >= 60) {
                newPassList.add(score);
                passCount++;
            }
        }

        System.out.println("PassGrade: " + newPassList);
        System.out.printf("SumGrade: %d\n", total);
        System.out.printf("MINGrade: %d\n", min);
        System.out.printf("MAXGrade: %d\n", max);
        System.out.printf("PassCount: %d\n", passCount);
    }
}
1赞 libing 8/30/2023 #2

复制一个新数组并打印。

System.out.println("PASS grade: " + Arrays.toString(Arrays.copyOf(newPassArray, passingIndex)));