java-如何在新行前显示数字 5 次



所以我知道我必须得到其余的才能工作。但是,它运行良好,除了第一行它给了我 6 而不是第一行的 5。我认为发生这种情况是因为 0 被认为是 5 的倍数,但我不确定如何解决这个问题。我看了 如何每行显示 5 个倍数?但是我无法看到如何使用它修复我的代码,因为它看起来不像他们有第一行被搞砸的问题。例如,如果我在正数中输入 17,它的第一行给出 6 个数字,其余部分给出 5 个数字。然后它给出剩下的,这就是我想要的。对于平均部分,您可以键入任何内容,因为我稍后将对此进行处理。所以格式应该是这样的:

4.50, 5.56, 2.73, 8.59, 7.75,

5.34, 3.65,

这是我的代码,感谢您的帮助:

import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayFun {
    public static void main(String[] args) {
        ArrayFun a = new ArrayFun();
    }
    public ArrayFun() { 
        Scanner input = new Scanner(System.in);
        // Get input from the user 
        System.out.print("Enter a positive number: "); 
        int limit = input.nextInt();
        // Get input from the user 
        System.out.print("Enter the lower bound for average: "); 
        double lowerBound = input.nextDouble();
        // Generate an array of random scores
        double[] allScores = generateRandomArrayOfScores(limit);
        // Display scores, wrapped every 5 numbers with two digit precision 
        DecimalFormat df = new DecimalFormat("0.00"); 
        displayArrayOfScores(allScores , df);
        // Calculate the average of the scores and display it to the screen
        //double average = calculateAverage(lowerBound , allScores); //
        System.out.print("Average of " + limit + " scores "); 
        System.out.print("(dropping everything below " + df.format(lowerBound) + ") "); 
        //System.out.println("is " + df.format(average) );//
    }
    private double[] generateRandomArrayOfScores(int num) {
        double[] scores=new double[num];
        for (int i=0;i<scores.length;++i) {
            double number=Math.random()*100.0;
            scores[i]=number;
        }
        return scores;
    }
    private void displayArrayOfScores(double[] scores, DecimalFormat format) {
        System.out.println("Scores:");
        for (int i=0;i<scores.length;++i) {
            String num=format.format(scores[i]);
            if ((i%5==0)&&(i!=0)) {
                System.out.println(num+", ");
            }
            else{
                System.out.print(num+", ");
            }
        }
        System.out.println();
    }

}

问题确实是 0,正是这部分(i%5==0)&&(i!=0)。将其替换为i%5==4,它应该可以工作。这是因为System.out.println(...)在打印字符串后制作新行,如果您计算 0,1,2,3,4,5,那是 6 个数字,因为您对待 0 的方式不同。5 组中的最后一个数字的模数为 4。 (i+1)%5==0当然会太有效,它是等效的。或者,您可以使用您的条件进行空System.out.println(),然后打印数字作为其他数字。

最新更新