gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:10:18 27 4
gpt4 key购买 nike

我希望获得一些帮助来解决每五个数字后换行的问题。我将 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);

}
}

最佳答案

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

关于java - 如何在每 5 个数字后开始一个新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59497234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com