簡體   English   中英

Java - 將文件讀入對象數組

[英]Java - read file into array of objects

我需要一些指導。 我不確定如何將示例文本文件讀入對象數組。 我知道這項工作需要在我在 main 中的 while 循環中進行。 我只是不知道我需要什么來完成這個。

我知道我需要逐行讀取文件(這就是 while 循環所做的),但我不知道如何將該行解析為數組中的對象。

我知道你們所有人都喜歡在提供幫助之前先看看人們嘗試過什么,但老實說我不知道該嘗試什么。 我不需要施舍,只需要一些指導。

示例文本文件:

100 3
120 5
646 7
224 9
761 4

主要的:

public static void main(String[] args) {

    Weight[] arrWeights = new Weight[25];
    int count = 0;

    JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

    int returnValue = jfc.showOpenDialog(null);

    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = jfc.getSelectedFile();
        System.out.println(selectedFile.getAbsolutePath());

        BufferedReader inputStream = null;
        String fileLine;

        inputStream = new BufferedReader(new FileReader(selectedFile.getAbsoluteFile()));

        System.out.println("Weights:");

        // Read one Line using BufferedReader
        while ((fileLine = inputStream.readLine()) != null) {
            count++;
            System.out.println(fileLine);
        }

        System.out.println("Total entries: " + count);
    }
}

體重等級:

public class Weight {

    private int pounds;
    private double ounces;
    private final int OUNCES_IN_POUNDS = 16;

    public Weight(int pounds, double ounces) {
        this.pounds = pounds;
        this.ounces = ounces;
    }

    public boolean lessThan(Weight weight) {
        return toOunces() < weight.toOunces();
    }

    public void addTo(Weight weight) {
        this.ounces += weight.toOunces();
        normalize();
    }

    public void divide(int divisor) {
        if (divisor != 0) {
            this.ounces = (this.toOunces() / divisor);
            this.pounds = 0;
            normalize();
        }
    }

    public String toString() {
        return this.pounds + " lbs " + String.format("%.3f", this.ounces) + " oz";
    }

    private double toOunces() {
        return this.pounds * OUNCES_IN_POUNDS + this.ounces;
    }

    private void normalize() {
        if (ounces >=16) {
            this.pounds += (int) (this.ounces /OUNCES_IN_POUNDS);
            this.ounces = this.ounces % OUNCES_IN_POUNDS;
        }
    }
}

我不記得如何在 Java 中完全做到這一點,但我認為這個一般指南可以幫助你:

在 while 循環中 -

  1. 使用 split 函數解析您從讀取行輸入的行,您可以將其用作參考(第一個示例可以解決問題):http: //pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString .html

  2. 獲取解析后的行值,將它們轉換為每個類所需的值並創建對象。

  3. 將創建的對象附加到您的對象列表中:arrWeights

暫無
暫無

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

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