亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

while 循環中的掃描儀陷入無限循環

while 循環中的掃描儀陷入無限循環

MYYA 2024-01-05 15:08:15
我有以下代碼,它似乎陷入了 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 32 9863 4 6 1 9
查看完整描述

2 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

問題是這樣的:

Scanner scanner = new Scanner(System.in);

您完全忽略了正在打開的文件,而是從標準輸入中讀取。它實際上并不是無限循環;而是無限循環。它正在等待輸入。


查看完整回答
反對 回復 2024-01-05
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

您的代碼不是在讀取文件;而是在讀取文件。它正在等待您輸入內容。


如果你想讀取一個文件,你需要將文件傳遞給 Scanner ,而不是System.in.


然而,與使用 BufferedReader 或最好使用 Streams 相比,使用 Scanners 通常是錯誤的文件讀取模式


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


try (Stream<String> stream = Files.lines(Paths.get("in.txt"))) {

    stream.flatMap(line -> Arrays.stream(line.split("\\s+")))

            .map(Integer::parseInt)

            .forEach(integerList::add);

} catch (IOException e) {

    e.printStackTrace();

}


System.out.println(integerList);


查看完整回答
反對 回復 2024-01-05
  • 2 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號