我在数组中放了几个元素(例如5个元素) 第一个元素,数组的index [0]将自动显示,用户无需单击该按钮。
单击按钮后,它将打印数组的下一个元素,并继续进程直到数组的最后一个元素。每次点击按钮,文件都会写在txt文件上。
我的问题是,例如数组的5个元素(单击按钮时成功显示),但只有四个文件写在txt文件中。怎么做到五...... Helppp ......我走在死路上: - (
public class mainFrame extends JFrame implements ActionListener {
........
private JButton answer1 = new JButton();
String [] a = {"a","b","c","d","e"}
in fileNumber = 0;
}
public mainFramme (){
System.out.println(a.get(fileNumber))
fileNumber++;
answer1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource==answer1) {
System.out.println(a.get(fileNumber))
try {
.....
fout = new FileOutputStream ("myfile.txt",true);
Filename = new File(files.get(fileNumber));
new PrintStream(fout).println (Filename);
new PrintStream(fout).println ("Answer 1");
fileNumber++;
}
...
}
}
答案 0 :(得分:1)
你的问题在于:
public mainFramme (){
System.out.println(a.get(fileNumber))
fileNumber++
answer1.addActionListener(this);
}
你在按下按钮之前递增fileNumber所以它等于1.数组在Java中从0开始索引,意味着获取你使用的数组中的第一个元素 array [0] - 看到当fileNumber等于1时,你将得到数组的第二个元素 - 因此错过了第一个。
根据评论编辑:
好的,那你在文件输出流上调用flush()和close()方法吗? 'flush'确保流中的任何数据在关闭之前写出。如果您发布整个actionPerformed方法,它可能会有所帮助。
您发布的一些代码也不理想(即新的PrintStream内容)
也许这可能会有所帮助:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == answer1) {
try {
PrintWriter output = new PrintWriter(new FileOutputStream(fileName.txt));
// Write stuff to file using output.printLn();
output.flush();
output.close();
}catch (IOException e) { // exception handling }
}
}
答案 1 :(得分:0)
在构造函数中,您有
System.out.println(a.get(fileNumber))
fileNumber++;
在我看来,就像你将一个字符串打印到stdout(即屏幕)而不将其写入文件。我敢打赌,这就是为什么你错过了文件中的一个数组元素。
答案 2 :(得分:0)
在创建第一个文件(第0个元素)之前递增文件编号值。这导致4个文件,即索引1-4中的元素。未创建第0个文件。
答案 3 :(得分:0)
你缺少一堆分号 - 我不确定这是否导致问题(甚至不应该运行)
确保每行需要分号。
答案 4 :(得分:0)
其他人已经基本回答了,但是根据你的评论,我认为不清楚。您将自动向屏幕显示第一个字符串,但不会显示文件。最好将文件操作移出actionPerformed()方法。你编写它的方式,只有在按下按钮时才会调用文件操作,对于第一个字符串来说绝对不是这样。
这可能更清楚:
public class mainFrame extends JFrame implements ActionListener {
........
private JButton answer1 = new JButton();
String [] a = {"a","b","c","d","e"}
in fileNumber = 0;
}
public mainFrame (){
nextString();
answer1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource==answer1) nextString();
}
private void nextString() {
try {
.....
System.out.println(a.get(fileNumber))
fout = new FileOutputStream ("myfile.txt",true);
Filename = new File(files.get(fileNumber));
new PrintStream(fout).println (Filename);
new PrintStream(fout).println ("Answer 1");
fileNumber++;
}
...
}