第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

while 循環(huán)中的掃描儀陷入無(wú)限循環(huán)

while 循環(huán)中的掃描儀陷入無(wú)限循環(huán)

MYYA 2024-01-05 15:08:15
我有以下代碼,它似乎陷入了 while 循環(huán),但我不明白為什么。注釋掉 while 循環(huán)可以讓代碼干凈地運(yùn)行。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;    }}我嘗試在幾個(gè)地方添加打印語(yǔ)句來(lái)縮小錯(cuò)誤的范圍。代碼執(zhí)行到 while 循環(huán),然后卡住,必須手動(dòng)停止。然而,讓我有點(diǎn)失望的是,我在 while 循環(huán)的頂部添加了一條 print 語(yǔ)句,但我什么也沒(méi)得到。所以它實(shí)際上并沒(méi)有執(zhí)行 while 循環(huán)本身中的任何代碼,但這就是它被卡住的地方?輸入文件2 8 32 9863 4 6 1 9
查看完整描述

2 回答

?
qq_花開(kāi)花謝_0

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊

問(wèn)題是這樣的:

Scanner scanner = new Scanner(System.in);

您完全忽略了正在打開(kāi)的文件,而是從標(biāo)準(zhǔn)輸入中讀取。它實(shí)際上并不是無(wú)限循環(huán);而是無(wú)限循環(huán)。它正在等待輸入。


查看完整回答
反對(duì) 回復(fù) 2024-01-05
?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊

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


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


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


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);


查看完整回答
反對(duì) 回復(fù) 2024-01-05
  • 2 回答
  • 0 關(guān)注
  • 157 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)