gpt4 book ai didi

java - 意外的输出...这个输出无论如何都不是我所期望的。这是什么

转载 作者:行者123 更新时间:2023-12-01 18:40:27 25 4
gpt4 key购买 nike

我希望给定的代码在 src 文件夹中名为 OutFile.txt 的文本文件中写入以下内容(并且该文件的副本存在于项目的主目录中,其中存在 src 和 res 等其他文件夹)本项目简介:

Value at: 0 = 0
Value at: 1 = 1
Value at: 2 = 2

但它不会在文件中写入任何内容。并在控制台中给出以下输出:

0
0

0
0
0

代码:-

package exception_handling_1;

//Note: This class won't compile by design!
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class ListOfNumbers {

private List<Integer> list;
private static final int SIZE = 3;

public ListOfNumbers () {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}


static PrintWriter out;

public void writeList() {
//PrintWriter out=null;
try{
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
}catch (Exception e){
System.out.println("IO Exception!");
}finally {
out.close();
}
}


}

请告诉我为什么会得到这个输出。谢谢。

最佳答案

现在它工作正常,正如您猜测的输出

package com.prectice;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class ListOfNumbers {

private List<Integer> list;
private static final int SIZE = 3;

public ListOfNumbers () {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}


static PrintWriter out;

public void writeList() {
//PrintWriter out=null;
try{
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
System.out.println("Value at: " + i + " = " + list.get(i));
}
}catch (Exception e){
System.out.println("IO Exception!");
}finally {
out.close();
}
}
public static void main (String[] args){
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}


}

关于java - 意外的输出...这个输出无论如何都不是我所期望的。这是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20099974/

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