我正在制作一个骰子滚动项目,并希望将我的项目保存到.txt或.pdf文件中,以便我可以在excel中绘制图形。我刚刚学会了如何将程序保存为计算机科学课程中的文件,但有时我很难理解我的教授。有人能指出我所缺少的东西,并可能稍微解释一下这个概念吗?我试图谷歌某种解释,但我需要的是关于如何将其保存到文件的准系统解释。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import javax.swing.JOptionPane;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static Random rnd = new Random();
private final static int FACENUMBER = 6;
static String output = "output.txt";
static File file = new File(output);
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
System.out.println();
int total[] = new int[(M)+1];
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt((FACENUMBER-1)*N)+N;
}
System.out.printf("%3s%12s\n", "Rolls"," Sum of Rolls");
for(int k=1; k<total.length; k++){
System.out.printf("%3s%12s\n", k, total[k]);
}
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output);
writer.close();
}catch(IOException e){
System.out.println("Can't open "+output);
return;
}
}
}
答案 0 :(得分:0)
当您尝试写入writer时,您尝试将输出作为变量传递:
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output);
writer.close();
}
但是,输出是您的文本文件。
所以你需要创建一个String变量来获取for循环的结果:
for(int k=1; k<total.length; k++){
System.out.printf("%3s%12s\n", k, total[k]);
}
相反,您可以使用以下内容:
String yourString=""; //Empty string
for(int k=1; k<total.length; k++){
yourString=yourString + "%3s%12s\n" + k + total[k];
}
然后而不是使用:
writer.write(output)
使用:
writer.write(yourString);