如何在每第 5 个数字后开始一个新行?

How can I start a new line after every 5th number?

我希望得到一些帮助来解决每五个数字后换行的问题。我将 1 到 90 之间的随机数放入一个数组列表中,然后将其写入一个文件中。 (稍后我想对列表和类似的所有内容进行排序,因此我使用 ArrayList 而不是立即将数字写入文件。)

public class Lotto {

    static ArrayList<Integer> list = new ArrayList();


    public static void main(String[] args) throws IOException {


          randomNumber();
          fileReader();
    }

    public static void printHeader() {
        System.out.println("Week"
                + "|Numbers                           "
                + "\n"
                + "----+"
                + "-----------------------+");
    }

    public static void randomNumber() {
        int num;
        int n = 5;

      //  String str = String.valueOf(num);

        list = new ArrayList<>();
        try {


            FileWriter writer = new FileWriter("/Users/xyz/desktop/lotto2010.txt");
            BufferedWriter bw = new BufferedWriter(writer);

            for (int i = 1; i <= 260; i++) {
            double number = Math.random() * 90;

            num = (int) number;


            list.add(num);
            if((i % n) == 0) bw.newLine();

            }

            bw.write(list.toString());
            bw.close();

        } catch (IOException ex) {
            System.out.println("Couldn't write the file or directory doesn't exist" + ex.getMessage());
        }
    }

    public static void fileReader() throws IOException {


        FileReader fileReader = new FileReader("/Users/xyz/desktop/lotto2010.txt");
        String allText;
        try (PrintWriter writer = new PrintWriter("/Users/xyz/desktop/lotto2011.txt")) {
            BufferedReader br = new BufferedReader(fileReader);


            allText = br.readLine();

                writer.print(allText);            

        }
        System.out.println(allText);

    }
}

添加 loop,检查 i % 5 == 0,添加 /nbw.newLine();

伪代码:

for (int i = 0; i < array.size(); i++{
    println(array(i));
    if(i % 5 == 0){
        println();
    }
}

这将完成所需,您正在做的是,在生成数字时将其添加到列表中并在每 5 个数字后同时写一个 newline .虽然你应该在遍历数组时这样做。在迭代之前,您可以使用排序或任何

修改您的数组
FileWriter writer = new FileWriter("/Users/xyz/desktop/lotto2010.txt");
BufferedWriter bw = new BufferedWriter(writer);

for (int i = 1; i <= 260; i++) {
    double number = Math.random() * 90;
    num = (int) number;
    list.add(num);
}

// optional step like sorting, as per your question
Collections.sort(list);

for (int i = 0; i < list.size(); i++) {
     bw.write(list.get(i).toString());
     if(i!=0 && i % n == 0) {
         bw.newLine();
     } else {
         bw.write(", ");
     }
}

bw.close();

得到这样的输出 -

9, 10, 10, 10, 11
11, 11, 12, 12, 13
13, 13, 13, 13, 13
14, 14, 14, 14, 15
16, 16, 17, 17, 17
18, 18, 19, 19, 19
19, 20, 21, 21, 21
22, 23, 23, 23, 23
23, 24, 24, 24, 25
26, 26, 26, 26, 26
.............