gpt4 book ai didi

java - PrintWriter 不写入 java 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:00 24 4
gpt4 key购买 nike

几个小时以来,我一直在尝试将我的代码打印到记事本。基本上我创建一个文件并在其中放入 10 个随机整数。然后我创建另一个文件,将第一个文件中的 10 个随机整数乘以 10。我尝试了刷新、打开关闭等。我假设我的代码中存在问题。谢谢!

    import java.io.File;


import java.util.Random;
import java.io.PrintWriter;
public class UghFiles {

public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

Random rand = new Random();
int x = 0;
File file = new File("LearnProgram.txt");

if(file.exists()) {

System.out.println("File alrady exists");
System.exit(0);
}
else {
PrintWriter output = new PrintWriter(file);
for(int i= 0; i<10; i++){
x = 0 + rand.nextInt(99-0)+1;

output.print(x);
//System.out.print(x + " ");
//System.out.print("");

}
output.close();
}
File f2 = new File("Multiply.txt");
if(f2.exists()) {

System.out.println("File already exists");
System.exit(0);
}
else {
java.util.Scanner input = new java.util.Scanner(file);
PrintWriter output = new PrintWriter(file);

while(input.hasNext()) {
x = x*10;

output.println("" + x);
System.out.print(x);
}
output.close();
input.close();
}

}
}

最佳答案

这里有一些错误。

首先,您几乎肯定希望数字出现在不同的行上而不是连接在一起:

for(int i= 0; i<10; i++){
x = 0 + rand.nextInt(99-0)+1;
output.print(x);
//System.out.print(x + " ");
//System.out.print("");
}

...所以第三行应该是 output.println(x);

其次(也是最重要的):

java.util.Scanner input = new java.util.Scanner(file);
PrintWriter output = new PrintWriter(file);

您忽略了刚刚创建的 f2,并且几乎肯定要写入。 (因此第二个参数应该是 f2。)这就是为什么你的文件是空的 - 它实际上被写入你上面的代码中很好,只是在这一步被空数据覆盖!

第三:

while(input.hasNext()) {
x = x*10;

您只是一次又一次地乘以相同的数字,而不是实际从您的扫描仪中读取。您几乎肯定希望用 x = input.nextInt() * 10; 代替。

关于java - PrintWriter 不写入 java 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152265/

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