簡體   English   中英

Java-將.txt文件讀取到arrayList省略最后一次迭代並顯示錯誤

[英]Java - reading .txt file to arrayList omits last iteration and shows error

我有一個.txt文件,要求將其內容放入arraylist中。 它采用以下格式,每個元素(int,String)位於文檔中的新行上。

int零件數字符串partname字符串描述int價格字符串partname字符串描述int price等。

每當我運行程序時,它將添加第一個但很多屬性,但不會將最后三個屬性添加到arraylist。

    public static void loadPartsCleanly(){  

    try {
    //  java.io.File file = new java.io.File("parts.txt");

        Scanner in = new Scanner(new File("parts.txt"));
        ArrayList<Part> partlist = new ArrayList<Part>();

        String name=null;
        String description = null;
        double price =0.0;
        int totalParts = 0;

        totalParts = in.nextInt();
        in.nextLine();
    //totalParts ++ ;

        System.out.println(totalParts);

        for (int i = 0; i < totalParts; i++)
        {           
        //ArrayList<Part> partlist = new ArrayList<Part>();
             name = in.nextLine();
             description = in.nextLine();
             price = in.nextDouble();
             in.nextLine();

        int quantityInStock = 5;


        partlist.add(new Part(name, description, price, quantityInStock));

        System.out.println(partlist);
        }

        in.close();
    } catch (FileNotFoundException fnfe) {
        System.out.println("Unable to locate the parts.txt file for opening.");


    } catch (Exception otherExc) {

        System.out.println("***** An unexpected error has occurred *****");
        otherExc.printStackTrace();
    }


}

因此,在上面的代碼中,它將讀取文本文檔中的第一個Int並將其分配給for循環。

    totalParts = in.nextInt();
        in.nextLine();
    //totalParts ++ ;

        System.out.println(totalParts);

        for (int i = 0; i < totalParts; i++)

循環工作正常,直到需要將最后一個部分添加到arraylist中,無論totalParts是8還是20。

這給出了這個錯誤..

發生意外錯誤java.util.NoSuchElementException:找不到行

我一直在試圖解決這個問題,但是越來越多的挫敗感促使我在這里發表文章,因此,向正確方向提出的任何建議將不勝感激。 如果您需要任何有關我的問題的說明,請詢問。

nextInt()nextDouble()方法與nextLine()不同。 nextLine()讀取\\ n,但其他的讀取。

因此,如果每個元素都位於不同的行中,則應始終使用nextLine() ,然后將該行解析為所需的類型,例如:

String line = in.nextLine();
double price = Double.parseDouble(line);

我認為您輸入文件的最后一行是數字。 我從您的代碼中看到的是,您使用nextDouble讀取價格,然后使用nextLine轉到下一行。 在這種情況下,如果最后一個數字后面沒有其他行,那么您將出錯。

以下代碼解決了您的問題。

if (i + 1 < totalParts) {
    in.nextLine();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM