所以我知道我必须得到剩余的部分才能使其发挥作用。然而,它工作得很好,除了第一行,它给了我 6 而不是 5。我认为发生这种情况是因为 0 被认为是 5 的倍数,但我不太确定如何解决这个问题。我看了How to display 5 multiples per line?但我很难看到如何使用它来修复我的代码,因为看起来他们没有第一行被搞乱的问题。例如,如果我在正数中输入 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()
,然后将数字打印为其他数字。
关于Java-如何在换行前显示数字 5 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48393159/