如何使用文本文件中的记录创建对象 (Java)

huangapple go评论97阅读模式
英文:

How to Create Objects Using Records in a Text File (Java)

问题

我在为我的Java课程编写一个程序,其中我正在使用一个对象(服装物品)文件,该文件表示商店的库存。每个零售商品都有四个属性:int itemNumber、String description、int numInInventory和double price。

我正在努力弄清楚如何从文件中读取每一行并将每一行转换为对象。我首先想到的是创建一个while循环,其中包括类似currentItemNumber、currentDescription等的变量。所以我尝试了这个:

while (file.hasNextLine()) {
    currentItemNumber = file.nextInt();
    currentDescription = file.next

} // end while

但我在这里陷入了困境,因为每次我从Scanner中读取String时,我总是使用nextLine。但在这里不能使用,因为每一行包含对象的多个属性,不是行内的字符串。在我试图使用的结构中是否有一种方法可以做到这一点,或者我应该以不同的方式进行?我知道我曾经见过并且做过一些将String解析成单独部分的事情,我看过有人称之为“标记”的东西。人们是否建议逐行阅读然后将其解析为单独的标记,然后将每个标记分配给其适当的属性?然后我猜我必须将这些标记转换为适当的对象,因为我认为将整行读取然后解析它会使每个部分都变成一个字符串。

这是文本文件中的示例(根据教授的说明,不能以任何方式更改):

1000     Pants      10     19.99
2000     Jeans       2     25.95
3000     Shirt      12     12.50

如果您有相关的智慧,提前感谢您。

英文:

I'm working on a program for my Java class where I'm using a file of objects (clothing items) that represents inventory for a store. Each Retail_Item has four attributes: int itemNumber, String description, int numInInventory, and double price.

What I'm trying to figure out is how to read in each line from the file and turn each line into an object. My first thought was to create a while loop with vars like currentItemNumber, currentDescription, etc. So I tried this:

while (file.hasNextLine()) {
    currentItemNumber = file.nextInt();
    currentDescription = file.next

} // end while

But I got stuck there because every other time I've read in a String to a Scanner, I've always used nextLine. Can't use that here though, because each line contains multiple attributes of the object, not a String within a line. Is there a way to do this in the structure I'm trying to use, or should I be doing this a different way? I know I've seen and done some things where I parsed a String into separate pieces which I've seen people refer to as "tokens." Would people recommend reading each line in and then parsing it into separate tokens, then assigning each token to its appropriate attribute? Then I guess I'd have to cast those tokens into the appropriate object, since I think reading the whole line in and then parsing it would make each piece a String.

Here's a sample of what's in the text file (which can't be changed in any way, per the professor's instructions):

1000     Pants      10     19.99
2000     Jeans       2     25.95
3000     Shirt      12     12.50

Thanks in advance for your sage wisdom if you've got it.

答案1

得分: 1

以下是代码的翻译部分:

public class RetailItem {
    private static final int FIELDS = 4;

    private int itemNumber;
    private String description;
    private int numInInventory;
    private double price;

    public RetailItem(int itemNumber, String description, int numInInventory, double price) {
        this.itemNumber = itemNumber;
        this.description = description;
        this.numInInventory = numInInventory;
        this.price = price;
    }

    @Override // java.lang.Object
    public String toString() {
        return String.format("%4d %-5s %2d %2.2f", itemNumber, description, numInInventory, price);
    }

    public static void main(String[] args) {
        try (Scanner file = new Scanner(Paths.get("clothes.txt"))) {
            while (file.hasNextLine()) {
                String record = file.nextLine();
                String[] fields = record.split("\\s+");
                if (fields.length == FIELDS) {
                    int itemNumber = Integer.parseInt(fields[0]);
                    String description = fields[1];
                    int numInInventory = Integer.parseInt(fields[2]);
                    double price = Double.parseDouble(fields[3]);
                    RetailItem item = new RetailItem(itemNumber, description, numInInventory, price);
                    System.out.println(item);
                }
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}
英文:

The following code fulfills your requirement as stated in your question, namely how to create an instance of class RetailItem from a line of text from your text file. I presume it uses things that you may not have learned yet, like class Paths and try-with-resources. This is just used to scan through your file.

First, class RetailItem contains the members you described in your question. Next, I wrote a constructor for class RetailItem that creates a new instance and initializes the instance members. Then I wrote a toString() method that displays the contents of a RetailItem object in "human readable" form. Finally a main() method that reads your text file (which I named "clothes.txt"), line by line - using a Scanner. For each line read, the code splits it using a delimiter which consists of at least one whitespace character. (I presume you haven't yet learned about regular expressions in java.) Then I convert the elements of the String array returned by method split() into appropriate data types that are required by the RetailItem constructor. Then I call the constructor, thus creating an instance of class RetailItem (as you requested) and I print the created instance.

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;

public class RetailItem {
    private static final int FIELDS = 4;

    private int itemNumber;
    private String description;
    private int numInInventory;
    private double price;

    public RetailItem(int itemNumber, String description, int numInInventory, double price) {
        this.itemNumber = itemNumber;
        this.description = description;
        this.numInInventory = numInInventory;
        this.price = price;
    }

    @Override // java.lang.Object
    public String toString() {
        return String.format("%4d %-5s %2d %2.2f", itemNumber, description, numInInventory, price);
    }

    public static void main(String[] args) {
        try (Scanner file = new Scanner(Paths.get("clothes.txt"))) {
            while (file.hasNextLine()) {
                String record = file.nextLine();
                String[] fields = record.split("\\s+");
                if (fields.length == FIELDS) {
                    int itemNumber = Integer.parseInt(fields[0]);
                    String description = fields[1];
                    int numInInventory = Integer.parseInt(fields[2]);
                    double price = Double.parseDouble(fields[3]);
                    RetailItem item = new RetailItem(itemNumber, description, numInInventory, price);
                    System.out.println(item);
                }
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

答案2

得分: -1

我认为我会这样做,就像你说的那样,将每一行解析为单独的字符串,然后将每个部分分配给你正在构建的对象的实例变量。

我以前做过类似的事情,也许对你有帮助。

        Scanner fileScan;
        File babyNameFile = new File("yob2015.txt");
        
        try {
            fileScan = new Scanner(babyNameFile);
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在");
            return;
        }
        
        String currentLine;
        int numberOfGirlsNames = 0;
        
        while (fileScan.hasNextLine()) {
            String[] values;
            currentLine = fileScan.nextLine();
            values = currentLine.split(",");
            if (values[1].equals("F")) {
                numberOfGirlsNames = numberOfGirlsNames+1;
            }
        }
        System.out.println("女性名字的数量是:"+numberOfGirlsNames);
英文:

I think the way that I would do is, like you said, parse each line into separate strings and then assign each piece to instance variables of the object you are building.

I have done something like this before, maybe it can be helpful.

        Scanner fileScan;
File babyNameFile = new File("yob2015.txt");
try {
fileScan = new Scanner(babyNameFile);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
return;
}
String currentLine;
int numberOfGirlsNames = 0;
while (fileScan.hasNextLine()) {
String[] values;
currentLine = fileScan.nextLine();
values = currentLine.split(",");
if (values[1].equals("F")) {
numberOfGirlsNames = numberOfGirlsNames+1;
}
}
System.out.println("Number of female names was "+numberOfGirlsNames);

huangapple
  • 本文由 发表于 2020年4月8日 12:14:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/61093230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定