读取文件扫描仪方法。然后在 main 中创建数组列表

我是 Java 新手,遇到了这个问题。我需要在一个方法中读取一个充满整数的 txt 文件,然后我应该在 main 中调用它来创建一个 ArrayList。我似乎无法弄清楚。


这就是我所拥有的。


public class num {

    public static void main(String[] args) {

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

        list=  getFile();

        System.out.println("numbers are: " + list);

    }


    public static void getFile() {


        try {

            Scanner read = new Scanner(new File("numbers.txt"));


            do {

                int line = read.nextInt();

            }while (read.hasNext());


        } catch (FileNotFoundException fnf) {

            System.out.println("File was not found");

        }


        return line;

    }

}


波斯汪
浏览 165回答 2
2回答

Cats萌萌

尝试这个:public class num {public static void main(String[] args) {&nbsp; &nbsp; ArrayList<Integer> list = new ArrayList<Integer>();&nbsp; &nbsp; getFile(list);System.out.println("numbers are: " + list);}public static void getFile(ArrayList<Integer> list) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Scanner read = new Scanner(new File("numbers.txt"));&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; list.add(read.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; }while (read.hasNext());&nbsp; &nbsp; } catch (FileNotFoundException fnf) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("File was not found");&nbsp; &nbsp; }}基本上,您的getFile()方法是 void 类型,因此它不会返回任何内容。因此,您需要在此方法中将列表作为参数传递,然后更改该列表。然后您可以在主方法中查看更改。

叮当猫咪

您需要将方法的返回类型更改为 List 并将每个 nextInt 存储在本地 ArrayList 中,并且必须在最后返回本地列表!public class num {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ArrayList<Integer> list = getFile();&nbsp; &nbsp; &nbsp; &nbsp; list.forEach(System.out::println);&nbsp; &nbsp; }&nbsp; &nbsp; public static List<Integer> getFile() {&nbsp; &nbsp; &nbsp; &nbsp; List res = new ArrayList<Integer>();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scanner read = new Scanner(new File("numbers.txt"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.add(read.nextInt());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }while (read.hasNext());&nbsp; &nbsp; &nbsp; &nbsp; } catch (FileNotFoundException fnf) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("File was not found");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return res;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java