我编写了一个创建10个随机数的代码,我想将这些数字存储在一个文本文件中,但它只存储最后一个数字10次,我该如何解决?我对编码非常陌生,在此先感谢您!
<Col className="cond">
<div className="doubleCol">
{this.state.conditions
.filter(condition => !this.state.selectedSymptom.length || condition.symptoms.includes(this.state.selectedSymptom))
.map(item => (
<div>
<ListItem key={item.ObjectID} onClick={() => this.setState({ modalShow: true })}>
{item.name}
</ListItem>
<Modal animation={false} centered>
<Modal.Header closeButton>
<Modal.Title> {item.name}</Modal.Title>
</Modal.Header>
<Modal.Body> {item.description}</Modal.Body>
<Modal.Footer>
{item.link}
<Button onClick={() => this.setState({ modalShow: false })}>Close</Button>
</Modal.Footer>
</Modal>
</div>
))}
</div>
{/* Pull in names of conditions here. Each name should be clickable and call up full info on that condition */}
</Col>
答案 0 :(得分:1)
删除第一个循环,然后将随机化代码移至第二个循环,以显示为:
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!");
}
}
答案 1 :(得分:0)
基本上,您正在创建十个随机值,但是您永远不会使用前九个随机值,因为首先要计算随机值,然后再将变量添加十次到文件中。变量不能有10个不同的值!每次随机化数字时,都必须写出数字。所以:
for (int x = 0; x < 10; i++) {
int number = ran.nextInt(6) + 1;
try(PrintWriter file = new PrintWritter(new BufferedWritter(new FileWritter("test1.txt")));) {
file.println(number);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
您快到了。问题是您的file.println(number)行不在正确的循环中。确实,如果我阅读了您的代码,则首先给数字变量提供了10个随机整数,完成后,您将创建一个名为test1.txt的新文件,并将数字变量中的内容写入其中10次。这就是为什么同一整数在文件中出现10次的原因。 这种方法应该可以工作:
公共类骰子{
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);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File test1.txt has been created!");
}
}