java读取给定信息的文本文件

z9smfwbn  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(319)

所以我试图把一个文本文件drinks.txt转换成一个可以与之交互的自动售货机数组。我得到了以下代码:

import java.io.*;
import java.util.Scanner;

public class VendingMachine {

//data members
private Item[] stock;  //Array of Item objects in machine
private double money;  //Amount of revenue earned by machine

/*********************************************************************
 * This is the constructor of the VendingMachine class that take a
 * file name for the items to be loaded into the vending machine.
 *
 * It creates objects of the Item class from the information in the 
 * file to populate into the stock of the vending machine.  It does
 * this by looping the file to determine the number of items and then
 * reading the items and populating the array of stock. 
 * 
 * @param filename Name of the file containing the items to stock into
 * this instance of the vending machine. 
 * @throws FileNotFoundException If issues reading the file.

*********************************************************************/

public VendingMachine(String filename) throws FileNotFoundException{
    //Open the file to read with the scanner
    File file = new File(filename);
    Scanner scan = new Scanner(file);

    //Determine the total number of items listed in the file
    int totalItem = 0;
    while (scan.hasNextLine()){
        scan.nextLine();
        totalItem++;
    } //End while another item in file
    //Create the array of stock with the appropriate number of items
    stock = new Item[totalItem];
    scan.close();

    //Open the file again with a new scanner to read the items
    scan = new Scanner(file);
    int itemQuantity = -1;
    double itemPrice = -1;
    String itemDesc = "";
    int count = 0;
    String line = "";

    //Read through the items in the file to get their information
    //Create the item objects and put them into the array of stock
    while(scan.hasNextLine()){
        line = scan.nextLine();
        String[] tokens = line.split(",");
        try {
            itemDesc = tokens[0];
            itemPrice = Double.parseDouble(tokens[1]);
            itemQuantity = Integer.parseInt(tokens[2]);

            stock[count] = new Item(itemDesc, itemPrice, itemQuantity);
            count++;
        } catch (NumberFormatException nfe) {
            System.out.println("Bad item in file " + filename + 
                    " on row " + (count+1) + ".");
        }
    } //End while another item in file
    scan.close();

    //Initialize the money data variable.
    money = 0.0;
} //End VendingMachine constructor

} //End VendingMachine class definition

文本文件如下所示:

Milk,2.00,1 
OJ,2.50,6
Water,1.50,10
Soda,2.25,6
Coffee,1.25,4
Monster,3.00,5

总的来说,我只是想弄清楚如何在包含main方法的vendingmachinedriver类下读取drinks.txt。你们有什么建议吗?

edqdpe6u

edqdpe6u1#

您的文本文件已转换为数组

private Item[] stock;  //Array of Item objects in machine

此处插入元素的位置

stock[count] = new Item(itemDesc, itemPrice, itemQuantity);

你可以用这个 stock 类中的数组

for (int i = 0; i < stock.length; i++) {
    Item item = stock[i];
    // Do something with item
}

或者从外部用它做一些事情(你需要为此创建一个getter)
在班里

public Item getStockForIndex(int i) {
    return stock[i];
}

其中主代码是

VendingMachine vm = new VendingMachine("filename.txt");

// Get first item
Item item = vm.getStockForIndex(0);

// Do something with item
fnx2tebb

fnx2tebb2#

要声明并创建一个新的文本文件,请使用名称“newtextfile.txt”执行以下操作:

File newFile=new File("NewTextFile.txt");

这将在您正在处理的项目的当前目录中创建文本文件。如果您只想在newfile对象中分配已经存在于目录中的文件,那么上面的代码也可以使用。
希望这对你有帮助。

相关问题