gpt4 book ai didi

Java数组问题

转载 作者:行者123 更新时间:2023-12-01 16:12:15 24 4
gpt4 key购买 nike

我在数组中放入了几个元素(例如 5 个元素)数组的第一个元素索引[0]将自动显示,无需用户单击按钮。

单击按钮后,它将打印数组的下一个元素,并继续该过程,直到数组的最后一个元素。每次单击该按钮,都会在 txt 文件中写入一个文件。

我的问题是,有例如数组的 5 个元素(单击按钮时成功显示),但是只有 4 个文件写入 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++;
}
...
}

}

最佳答案

你的问题出在这里:

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 }
}
}

关于Java数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/671827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com