我如何为此添加一个return语句,以及如何调用该方法?

时间:2015-03-17 00:43:57

标签: java arraylist

public class InputFileData {
/**
 * @param inputFile a file giving the data for an electronic
 * equipment supplier’s product range
 * @return an array of product details
 * @throws IOException
 */
public static Product [] readProductDataFile(File inputFile) throws IOException {
// CODE GOES HERE (input data from a text file and sort into arraylists)
}

readProductDataFile用于读取文本文件,并将其存储在Product[]类型的数组中。提供的代码无法更改,我需要一种适用于此代码的方法。我设法让文件读取和排序到阵列列表在不同的类中工作,但以这种方式运行它给我带来了一些问题:

1)我无法从readProductDataFile课程调用Main方法,就像它无法找到方法一样(它肯定在正确的包中) )。

2)我无法弄清楚如何设置返回语句的格式,我尝试了很多不同的东西,但我无法看到如何将其存储为数组类型{{1} }。

到目前为止,我还没有提供很多具体的代码,因为我不希望答案在拼盘上交给我(这是作业的一部分所以我不想要其他人直接为我做这件事),但有人能够指出我正确的方向来解决这个问题吗?

为了了解我目前的工作方式,以下测试代码对我有用:

Product[]上课:

ElectronicsEquipmentDemo

public class ElectronicsEquipmentDemo { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Name inputFile = new Name(); inputFile.privateName(); } } 上课:

Name

从文本文件读取,如果行以 P 开头,则拆分为数组并打印出指定的值(尽管我尝试添加一个return语句使它只返回第一行,所以仍然在那里挣扎。)

2 个答案:

答案 0 :(得分:0)

这应该这样做:

public class Name {
    public String[] privateName(){
        String[] list;
        try {
            FileReader fr = new FileReader("myOutput.txt");
            BufferedReader br = new BufferedReader(fr);

            String str;

            while ((str = br.readLine()) != null) {
                char firstLetter = str.charAt(0);

                if (firstLetter == 'P'){

                    list = str.split("/");

                    //Arrays.toString(list);
                    String fullName = list[1] + " " + list[2] + " "+ list[3] + "\n";
                    System.out.println(fullName);

                }

            }
            br.close();
        } catch (IOException e) {
            out.println("File not found");
        }
        return list;

    }
}

编辑:修复了范围界定问题。

答案 1 :(得分:-1)

嗯,对于第一个问题,我唯一能注意到的是你的方法是static,所以一定要正确调用它。 另外,请考虑static是否真的符合您的需要。

对于第二个问题,return list.toArray(new String[list.size()])应该有效。

相关问题