我有一个项目,我需要获取用户输入然后执行体积计算,所有这些我已经完成了几个不同的形状。但是,我需要能够将每个形状的输入和计算存储到一个文件中,如果选择该文件,我以后可以从中读取。我尝试了几种不同的方式来做到这一点,但无济于事。除了我最近的尝试外,所有这些都给了我一个语法错误。但是,此尝试似乎并未写入文件,并且仅在一行上返回 0.0。任何帮助,将不胜感激
public JButton getCalculateButton()
{
JButton spa;
spa = new JButton("Calculate Volume");
spa.setMnemonic('C');
spa.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(",###.##");
double length, depth, volume;
String instring;
instring = lengthField.getText();
if (instring.equals("")){
instring = "0";
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = depthField.getText();
if (instring.equals("")){
instring = "0";
depthField.setText("0");
}
depth = Double.parseDouble(instring);
volume = length * 8 * 4.8284 * depth;
volumeField.setText(num.format(volume));
}
});
return spa;
}
public JButton getSaveButton(){
JButton save;
save = new JButton("Save Data");
save.setMnemonic('C');
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
PrintWriter writer;
try {
writer = new PrintWriter(new FileWriter("spaFile.txt"));
writer.printf(String.valueOf(length), String.valueOf(depth), String.valueOf(volume));
writer.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return save;
}
这是我的 GUI 的一部分,它进行计算并希望存储数据,但没有。
public JButton getSearchButton()
{
JButton search;
search = new JButton("Search");
search.setMnemonic('S');
search.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
FileInputStream fileStream;
try {
fileStream = new FileInputStream("spaFile.txt");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println(reader.readLine());
reader.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return search;
}
}
这是要阅读的部分,尽管我还没有将它完全作为 GUI 用于测试目的。