gpt4 book ai didi

java - 在文本文件中存储随机数 (Java)

转载 作者:行者123 更新时间:2023-12-02 09:16:32 25 4
gpt4 key购买 nike

我编写了一个创建 10 个随机数的代码,我想将这些数字存储在一个文本文件中,但它只存储最后一个数字 10 次,我该如何解决这个问题?我对编码非常陌生,提前致谢!

import java.io.*;
import java.util.Random;

public class Dices
{
public static void main( String[] args )
{
Random ran = new Random();
int number = 0;

for (int x = 0; x <10; x++) {
number = ran.nextInt(6)+1;
//System.out.println(number);

}



try (PrintWriter file = new PrintWriter(
new BufferedWriter(
new FileWriter("test1.txt")));
) {

for (int i = 1; i <= 10; i++) {
file.println(number);
}

} catch (IOException e) {
e.printStackTrace();
}

System.out.println("File test1.txt has been created!");


}
}

最佳答案

删除第一个循环并将随机化代码移至第二个循环,显示为:


package com.vinrithi.main;

import java.io.*;
import java.util.Random;

public class Dices {
public static void main(String[] args) {
Random ran = new Random();
int number = 0;
try (PrintWriter file = new PrintWriter(
new BufferedWriter(
new FileWriter("test1.txt")));
) {

for (int i = 1; i <= 10; i++) {
number = ran.nextInt(6) + 1;
file.println(number);
}
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("File test1.txt has been created!");
}
}

关于java - 在文本文件中存储随机数 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944201/

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