Java错误信息 "...在...中具有私有访问权限"

3

我在编写Java代码时遇到了一个问题。错误提示说,在我的代码中newLine()在PrintWriter中是私有的,我从未遇到过这种错误,这让我担心,因为我无法理解为什么newLine会对我的变量PrintWriterprivate的。

下面是我的错误信息和代码的一部分:

错误:

:75: error: newLine() has private access in PrintWriter
                        savingsFile.newLine();
                                   ^
:77: error: newLine() has private access in PrintWriter
                        savingsFile.newLine();
                                   ^
:96: error: cannot find symbol
        while((str1=savingsFile.readLine())!=null){
                               ^
  symbol:   method readLine()
  location: variable savingsFile of type Scanner
3 errors

代码:

    public static void writeToFile(String[] months, double[] savings) throws IOException{
    PrintWriter savingsFile = null;
    try {
        savingsFile = new PrintWriter(new FileWriter("E:/savings.txt", true));
    } catch (IOException e) {
        e.printStackTrace();
    }

    //code to write to the file and close it
    int ctr = 0;
    while(ctr<6){
            savingsFile.write(months[ctr]);
            savingsFile.newLine();
            savingsFile.write(savings[ctr]+"");
            savingsFile.newLine();
            ctr = ctr + 1;;
        }
        savingsFile.close();
    }

   public static void readFromFile(String[] months, double[] savings) throws IOException{
    String str1, str2;
    Scanner savingsFile = null;
    try {
        savingsFile = new Scanner(new File("E:/savings.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //code to read the file, load data in the array and close file
        str1 = savingsFile.nextLine();
        System.out.println(str1);
        int ctr = 0;
        while((str1=savingsFile.readLine())!=null){
            System.out.println(str1);
        }
        savingsFile.close();
    }
2个回答

4

PrintWriter没有公共的newLine()方法(参见Javadoc)。只需写入换行字符"\n"以创建新行,或者调用不带参数的println()

Scanner没有readLine()方法。您可能是想使用nextLine()


非常感谢你抽出时间帮助我!:) - undefined

2
似乎newLine()是PrintWriter中的一个私有方法,这意味着您无法从实例化PrintWriter的其他类外部调用它。

如何将其设为非私有? - undefined
@Sutdent_Sequej,你不能将它设为非私有。这是一个标准Java类的内部方法,所以你无法改变其可见性。请使用Jim Garrison的建议。 - undefined
非常感谢你今天的帮助! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接