帮助!代码保持返回为“nullnull”!我试图这样做,如果我有多个元素,它将显示在控制台中。这更像是一个两部分问题...... 1.我将多个不同的元素符号保存到一个变量中,它不会工作吗?我应该如何制作它以便每次都保存在不同的变量下? 2.为什么它一直作为nullnull返回?我认为应该将某些东西保存为元素1.虽然不太确定element11但是...... 谢谢你的帮助!
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import javax.swing.JOptionPane;
public class Science1 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String element;
int more;
FileInputStream fin;
JOptionPane.showMessageDialog(null, "Balancing chemical equations, capable for anything with more than one compound");
element = JOptionPane.showInputDialog("Please input an element");
String element1 = null;
element = element1;
String element11 = null;
//MORE VARIABLES?
more = JOptionPane.showConfirmDialog(null, "Do you have more elements on this side?", element, JOptionPane.YES_NO_OPTION);
while(more == 0){
element = JOptionPane.showInputDialog("Please input an element");
element = element11;
Writer writer = null;
try {
writer = new BufferedWriter(new FileWriter("test.txt"));
writer.write(element1 + element11);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
//MORE VARIABLES?
more = JOptionPane.showConfirmDialog(null, "Do you have more elements on this side?", element, JOptionPane.YES_NO_OPTION);
}
try
{
// Open an input stream
fin = new FileInputStream ("test.txt");
// Read a line of text
System.out.println( new DataInputStream(fin).readLine() );
// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read from file");
System.exit(-1);
}
}
}
答案 0 :(得分:0)
在阅读element
的输入后,您已将其分配给变量element1
null
。
element = JOptionPane.showInputDialog("Please input an element");
String element1 = null; //<<-----remove
element = element1; //<<-----remove
在BufferedWriter
循环之外初始化while
个实例。
如果您使用的是java 7,请使用try-with-resource语句自动为您关闭资源。
答案 1 :(得分:0)
替换
element = element1;
与
element1 = element;
和
element = element11;
带
element11 = element;
然后将每个新单词附加到文本文件
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
writer.println( element11);
writer.close();
} catch (IOException e) {
//!
}
答案 2 :(得分:0)
从本质上讲,你有这个:
String element1 = null;
String element11 = null;
while(more == 0){
try {
writer = new BufferedWriter(new FileWriter("test.txt"));
writer.write(element1 + element11);
但是你设置的是element1和element11。结果应该是什么?“nullnull”应该是什么?