while 循环中的扫描仪陷入无限循环

我有以下代码,它似乎陷入了 while 循环,但我不明白为什么。注释掉 while 循环可以让代码干净地运行。


import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.lang.Integer;


public class Main{

    public static void main(String[] pArgs)throws FileNotFoundException {

        Main mainObject = new Main();

        mainObject.run();

    }


    private void run() throws FileNotFoundException {

        readInputFile();


    }

    public ArrayList<Integer> readInputFile(){

        //reads input file and creates array of integers


        Scanner scanner = new Scanner(System.in);

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


        try {

            File in = new File("p01-in.txt");


            while (scanner.hasNext()){

                System.out.println("Tada!");

                int tempInt = scanner.nextInt();

                integerList.add(tempInt);

                return integerList;


            }


        }


        catch(Exception ioException){

            System.out.println("Oops, could not open 'p01-in.txt' for reading. The program is ending.");

            System.exit(-100);

        }


        finally {

            scanner.close();

        }

        return integerList;

    }

}

我尝试在几个地方添加打印语句来缩小错误的范围。代码执行到 while 循环,然后卡住,必须手动停止。然而,让我有点失望的是,我在 while 循环的顶部添加了一条 print 语句,但我什么也没得到。所以它实际上并没有执行 while 循环本身中的任何代码,但这就是它被卡住的地方?


输入文件


2 8 3

2 9

8

6

3 4 6 1 9


MYYA
浏览 52回答 2
2回答

qq_花开花谢_0

问题是这样的:Scanner&nbsp;scanner&nbsp;=&nbsp;new&nbsp;Scanner(System.in);您完全忽略了正在打开的文件,而是从标准输入中读取。它实际上并不是无限循环;而是无限循环。它正在等待输入。

跃然一笑

您的代码不是在读取文件;而是在读取文件。它正在等待您输入内容。如果你想读取一个文件,你需要将文件传递给 Scanner ,而不是System.in.然而,与使用 BufferedReader 或最好使用 Streams 相比,使用 Scanners 通常是错误的文件读取模式List<Integer> integerList&nbsp; = new ArrayList<>();try (Stream<String> stream = Files.lines(Paths.get("in.txt"))) {&nbsp; &nbsp; stream.flatMap(line -> Arrays.stream(line.split("\\s+")))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Integer::parseInt)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEach(integerList::add);} catch (IOException e) {&nbsp; &nbsp; e.printStackTrace();}System.out.println(integerList);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java