gpt4 book ai didi

java - "Attributes and objects cannot be resolved"- 错误

转载 作者:行者123 更新时间:2023-11-30 07:04:04 25 4
gpt4 key购买 nike

以下代码用于使用java读取或写入文件,但是:

Eclipse 打印这些错误:

  • buffer_1 无法解析为变量
  • 无法解析 file_reader
  • 还有其他属性...

这里的代码有什么问题:

    //Class File_RW
package R_2;

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;

public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}

//main method @ class Start:

package R_2;

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;

public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}

我找不到任何错误。我还尝试在“File_RW”类的构造函数中包含 try catch 语句,但错误消息是相同的。

最佳答案

是的,您的代码中存在错误 - 这些错误实际上是基本性质:您正在声明变量而不是字段。意思是:你在构造函数中有它们,但它们需要向上一层!当您在构造函数或方法中声明实体时,它就是一个仅存在于该构造函数/方法中的变量

如果您希望多个方法可以使用该实体,则它需要是一个字段,在封闭类的范围内声明,例如:

class FileRW {
private File fileToRead = new File...
...

然后您就可以在所有方法中使用您的字段!请注意:您可以在构造函数中进行实际设置:

class FileRW {
private File fileToRead;

public FileRW() {
fileToRead = ..

但你不必这样做。

最后:请阅读有关 java 语言约定的内容。您避免在名称中使用“_”(仅适用于 SOME_CONSTANT)!

关于java - "Attributes and objects cannot be resolved"- 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430682/

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