因此,我试图创建一个私有的静态方法,该方法将使用文本文件中的数据打印数组的内容。

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class hw2redo
{
    public static void main(String args[])
    {
         //Scan file for data
         GeometricObject g = null;
         BufferedReader file = new BufferedReader(new FileReader("file.txt"));
            Scanner diskScanner = new Scanner(file);
            //Create dynamic array list
            List<GeometricObject> list = new ArrayList<GeometricObject>();
            //Scan data and add data to list
            while(diskScanner.hasNext())
            {
                String geolist = diskScanner.nextLine();
                g = recreateObject(geolist);

                list.add(g);

            }

            private static GeometricObject recreateObject(String data)
            {
                System.out.println(data);
            }
    }

}


但是,我的recreateObject方法出现错误,说“对于类型hw2redo,未定义方法recreateObject(String)。”任何帮助或暗示我在做什么不正确,将不胜感激。谢谢!旁注:我只是在方法中放入任意内容,以查看错误是否是因为它为空。我只是想知道如何调用私有方法而不会收到错误。

最佳答案

您的recreateObject方法是在main方法中定义的。将其移到main的主体之外:

public class hw2redo
{
    public static void main(String args[])
    {
         //Scan file for data
         GeometricObject g = null;
         BufferedReader file = new BufferedReader(new FileReader("file.txt"));
            Scanner diskScanner = new Scanner(file);
            //Create dynamic array list
            List<GeometricObject> list = new ArrayList<GeometricObject>();
            //Scan data and add data to list
            while(diskScanner.hasNext())
            {
                String geolist = diskScanner.nextLine();
                g = recreateObject(geolist);

                list.add(g);

            }


    }

        private static GeometricObject recreateObject(String data)
        {
            System.out.println(data);
        }

}


(并且,显然,使其返回内容。)

10-06 01:30