【问题标题】:How do I write a method that has an ArrayList and an int as a parameter and returns an ArrayList如何编写具有 ArrayList 和 int 作为参数并返回 ArrayList 的方法
【发布时间】:2019-11-23 12:45:03
【问题描述】:

在编写将数组列表和整数作为输入的方法的标头时出现多个错误。

我尝试了几种不同的方法来编写该方法的标头。正文很好,给了我想要的东西,但我无法获取标题/调用名称(我不知道您调用方法的第一行)以不引发错误

       /**
         *  Creates Arraylist "list" using prompt user for the input and output file path and sets the file name for the output file to 
         *  p01-runs.txt
         *  
         */
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the path to your source file: ");
        String inPath = scan.nextLine(); // sets inPath to user supplied path
        System.out.println("Please enter the path for your source file: ");
        String outPath = scan.nextLine() + "p01-runs.txt"; // sets outPath to user supplied input path

        ArrayList<Integer> listRunCount = new ArrayList<Integer>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        /**
         *  Reads data from input file and populates array with integers.
         */
        FileReader fileReader = new FileReader(inPath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        // file writing buffer
        PrintWriter printWriter = new PrintWriter(outPath);

        System.out.println("Reading file...");

        /**
         * Reads lines from the file, removes spaces in the line converts the string to
         * an integer and adds the integer to the array
         */
        File file = new File(inPath); 
        Scanner in = new Scanner(file); 
        String temp=null;

        while (in.hasNextLine()) {
            temp = in.nextLine();
            temp = temp.replaceAll("\\s","");
            int num = Integer.parseInt(temp);
            list.add(num);
        }
            listRunCount.findRuns(list, RUN_UP);



//********************************************************************************************************          

        public ArrayList<Integer> findRuns(ArrayList<Integer> list, int RUN_UP){

            returns listRunCount;
        }

错误信息

Multiple markers at this line
    - Syntax error on token "int", delete this token
    - Syntax error, insert ";" to complete LocalVariableDeclarationStatement
    - Integer cannot be resolved to a variable
    - ArrayList cannot be resolved to a variable
    - Syntax error, insert ";" to complete LocalVariableDeclarationStatement
    - Illegal modifier for parameter findRuns; only final is permitted
    - Syntax error, insert ") Expression" to complete CastExpression
    - Syntax error on token "findRuns", = expected after this token
    - Syntax error, insert "VariableDeclarators" to complete 
     LocalVariableDeclaration
    - Syntax error, insert ";" to complete Statement

【问题讨论】:

  • 您的方法似乎是在另一个方法的中间声明的。那不是有效的Java。方法必须在类中声明,而不是在另一个方法中。
  • 你能把整个班级结构贴出来吗?正如@JB Nizet 所说,看起来您已经创建了一个方法而没有在 findRuns 之前关闭该方法。
  • 好的,我明白了!所以老师希望我们以这种方式开始我们的所有作业......
  • // Main.java public class Main { public static void main(String[] pArgs) { Main mainObject = new Main(); // 或者你可以直接写: new Main().run(); mainObject.run() // 代替这两行。 } private void run() { // 您将在此处开始编写代码以实现软件要求。 } }
  • 我现在看到 fileRuns 在 main 方法中。我可以解决这个问题。

标签: java arraylist methods


【解决方案1】:

这种东西消除了对静态的需求。如果您从静态方法 ma​​in() 中运行代码,则在 main() 中调用或引用的所有类方法、成员变量等也必须声明为 static强>。通过这样做:

public class Main {

    public static void main(String[] args) { 
        new Main().run(); 
    }

}

消除了对静态的需求。在我看来,要正确地做到这一点,类中的 run() 方法也应该传递 args[] 参数:

public class Main {

    public static void main(String[] args) { 
        new Main().run(args); 
    }

    private void run(String[] args) {
        // You project code here
    }

}

这样,任何传递给应用程序的命令行参数也可以在 run() 方法中进行处理。你会发现大多数人不会用run这个方法名来处理这类事情,因为run()是一个与线程运行更相关的方法名。 startApp() 之类的名称更合适。

public class Main {

    public static void main(String[] args) { 
        new Main().startApp(args); 
    }

    private void startApp(String[] args) {
        // You project code here
    }

}

考虑到这一切,您的代码可能看起来像这样:

public class Main {

    public static void main(String[] args) { 
        new Main().run(args); 
    }

    private void run(String[] args) {
        String runCountFileCreated = createListRunCount();
        if (!runCountFileCreated.equals("") {
            System.out.println(The count file created was: " + runCountFileCreated);
        }
        else {
            System.out.println(A count file was NOT created!);
        }
    }

     /**
     * Creates an ArrayList "list" using prompts for the input and output file
     * paths and sets the file name for the output (destination) file to an
     * incremental format of p01-runs.txt, p02-runs.txt, p03-runs.txt, etc. If
     * p01 exists then the file name is incremented to p02, etc. The file name
     * is incremented until it is determined that the file name does not exist.
     *
     * @return (String) The path and file name of the generated destination
     *         file.
     */
    public String createListRunCount() {
        String ls = System.lineSeparator();
        File file = null;

        Scanner scan = new Scanner(System.in);
        // Get the source file path from User...
        String sourceFile = "";
        while (sourceFile.equals("")) {
            System.out.print("Please enter the path to your source file." + ls
                    + "Enter nothing to cancel this process:" + ls
                    + "Source File Path: --> ");
            sourceFile = scan.nextLine().trim(); // User Input
            /* If nothing was entered (just the enter key was hit) 
                   then exit this method. */
            if (sourceFile.equals("")) {
                System.out.println("Process CANCELED!");
                return "";
            }
            // See if the supplied file exists...
            file = new File(sourceFile);
            if (!file.exists()) {
                System.out.println("The supplied file Path/Name can not be found!." + ls
                        + "[" + sourceFile + "]" + ls + "Please try again...");
                sourceFile = "";
            }
        }

        String destinationFile = "";
        while (destinationFile.equals("")) {
            System.out.print(ls + "Please enter the path to folder where data will be saved." + ls
                    + "If the supplied folder path does not exist then an attempt" + ls 
                    + "will be made to automatically created it. DO NOT supply a" + ls
                    + "file name. Enter nothing to cancel this process:" + ls
                    + "Destination Folder Path: --> ");
            String destinationPath = scan.nextLine();
            if (destinationPath.equals("")) {
                System.out.println("Process CANCELED!");
                return "";
            }
            // Does supplied path exist. If not then create it...
            File fldr = new File(destinationPath);
            if (fldr.exists() && fldr.isDirectory()) {
                /* Supplied folder exists. Now establish a new incremental file name.
                   Get the list of files already contained within this folder that 
                   start with p and a number (ex: p01-..., p02--..., p03--..., etc)
                 */
                String[] files = fldr.list();   // Get a list of files in the supplied folder.
                // Are there any files in the supplied folder?
                if (files.length > 0) {
                    //Yes, so process them...
                    List<String> pFiles = new ArrayList<>();
                    for (String fileNameString : files) {
                        if (fileNameString.matches("^p\\d+\\-runs\\.txt$")) {
                            pFiles.add(fileNameString);
                        }
                    }
                    // Get the largest p file increment number
                    int largestPnumber = 0;
                    for (int i = 0; i < pFiles.size(); i++) {
                        int fileNumber = Integer.parseInt(pFiles.get(i).split("-")[0].replace("p", ""));
                        if (fileNumber > largestPnumber) {
                            largestPnumber = fileNumber;
                        }
                    }
                    largestPnumber++;  // Increment the largest p file number by 1
                    // Create the new file name...
                    String fileName = String.format("p%02d-runs.txt", largestPnumber);
                    //Create the new destination File path and name string
                    destinationFile = fldr.getAbsolutePath() + "\\" + fileName;
                }
                else {
                    // No, so let's start with p01-runs.txt
                    destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
                }
            }
            else {
                // Supplied folder does not exist so create it.
                // User Confirmation of folder creation...
                JFrame iFrame = new JFrame();
                iFrame.setAlwaysOnTop(true);
                iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                iFrame.setLocationRelativeTo(null);
                int res = JOptionPane.showConfirmDialog(iFrame, "The supplied storage folder does not exist!"
                        + ls + "Do you want to create it?", "Create Folder?", JOptionPane.YES_NO_OPTION);
                iFrame.dispose();
                if (res != 0) {
                    destinationFile = "";
                    continue;
                }
                try {
                    fldr.mkdirs();
                }
                catch (Exception ex) {
                    // Error in folder creation...
                    System.out.println(ls + "createListRunCount() Method Error! Unable to create path!" + ls
                            + "[" + fldr.getAbsolutePath() + "]" + ls + "Please try again..." + ls);
                    destinationFile = "";
                    continue;
                }
                destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
            }
        }

        ArrayList<Integer> list = new ArrayList<>();

        /* Prepare for writing to the destination file.
           Try With Resourses is use here to auto-close 
           the writer.    */
        try (PrintWriter printWriter = new PrintWriter(destinationFile)) {
            System.out.println(ls + "Reading file...");

            /**
             * Reads lines from the file, removes spaces in the line converts
             * the string to an integer and adds the integer to the List.
             */
            String temp = null;
            /* Prepare for writing to the destination file.
               Try With Resourses is use here to auto-close 
               the reader.    */
            try (Scanner reader = new Scanner(file)) {
                while (reader.hasNextLine()) {
                    temp = reader.nextLine().replaceAll("\\s+", "");
                    /* Make sure the line isn't blank and that the 
                       line actually contains no alpha characters.
                       The regular expression: "\\d+" is used for
                       this with the String#matches() method.    */
                    if (temp.equals("") || !temp.matches("\\d+")) {
                        continue;
                    }
                    int num = Integer.parseInt(temp);
                    list.add(num);
                }

                // PLACE YOUR WRITER PROCESSING CODE HERE
            }
            catch (FileNotFoundException ex) {
                Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
            }
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
        }

        /* return the path and file name of the 
           destination file auto-created.    */
        return destinationFile; 
    }

}

【讨论】:

  • 哇!这非常有帮助!谢谢DevilsHnd!没有你们的帮助,我不会通过这门课!
猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 2014-04-23
  • 1970-01-01
  • 2014-11-17
  • 2016-04-05
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多