Java 将结果保存到文本文件
我现在正在做一个掷骰子的项目,我想把我的项目保存到一个.txt或.pdf文件中,这样我就可以在excel中绘制它。我刚在计算机科学课上学会了如何将程序保存为文件,但有时我很难理解我的教授。有人能指出我遗漏了什么并解释一下这个概念吗?我试着用谷歌搜索一些解释,但我所需要的只是关于如何将其保存到文件的简单解释Java 将结果保存到文本文件,java,arrays,format,save,Java,Arrays,Format,Save,我现在正在做一个掷骰子的项目,我想把我的项目保存到一个.txt或.pdf文件中,这样我就可以在excel中绘制它。我刚在计算机科学课上学会了如何将程序保存为文件,但有时我很难理解我的教授。有人能指出我遗漏了什么并解释一下这个概念吗?我试着用谷歌搜索一些解释,但我所需要的只是关于如何将其保存到文件的简单解释 import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IO
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;
}
}
}
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.util.Random;
导入javax.swing.JOptionPane;
公共类Lab1{
私有静态int N=0;
私有静态int M=0;
私有静态随机rnd=新随机();
专用最终静态int FACENUMBER=6;
静态字符串output=“output.txt”;
静态文件=新文件(输出);
公共标签1(){
}
公共静态void main(字符串[]args){
N=Integer.parseInt(JOptionPane.showInputDialog(“您想掷多少骰子?”);
System.out.println(“骰子:+N”);
M=Integer.parseInt(JOptionPane.showInputDialog(“您希望滚动多少次?”);
系统输出打印项次(“卷:+M);
System.out.println();
整数总计[]=新整数[(M)+1];
对于(int roll=1;roll当您尝试写入writer时,尝试将输出作为变量传递:
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output);
writer.close();
}
但是,输出是您的文本文件
因此,您需要创建一个字符串变量,该变量获取for循环的结果:
for(int k=1; k<total.length; k++){
System.out.printf("%3s%12s\n", k, total[k]);
}
使用:
您的意思是要将骰子结果保存到文件中吗?此时将创建一个名为output.txt的文件,其中包含output.txt是的,很抱歉我没有指定。我要将结果保存到文件中。
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);