Java/JavaFX – 购物车系统 – 将数据标记为 ArrayList

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

Java/JavaFX - Shopping Cart System - Tokenizing data into an Arraylist

问题

我正在做一个学校作业。我需要创建一个购物车系统,它在ListView中显示图书,并具有可以将这些图书添加到购物车或从购物车中删除的按钮/菜单项。

该程序应该读取一个名为"BookPrices.txt"的文件,并对字符串进行标记化,将单词与数字分开,然后将它们添加到两个ArrayList中。一个ArrayList用于存储图书标题,另一个用于存储图书价格。

我遇到的问题是,标记化代码似乎不起作用。我在addItemButton中使用一些println来测试ArrayList中是否有任何内容,到目前为止它们似乎是空的。请注意,标记化代码是从教科书中提供的,完整的程序还缺少操作数据和计算总成本的代码。

作业要求:
创建一个类似在线书店购物车系统的应用程序。当您的应用程序开始执行时,它应该读取文件的内容并将书籍标题存储在一个ListView中。用户应该能够从列表中选择一个标题并将其添加到一个"购物车"中,该购物车只是另一个ListView控件。应用程序应该具有允许用户从购物车中删除项目、清空购物车中的所有选择并结账的按钮或菜单项。当用户结账时,应用程序应该计算并显示购物车中所有书籍的小计、销售税(小计的7%)和总计。

BookPrices.txt文件内容如下:

I Did It Your Way,11.95
The History of Scotland,14.50
Learn Calculus in One Day,29.95
Feel the Stress,18.50
Great Poems,12.95
Europe on a Shoestring,10.95
The Life of Mozart,14.50

以下是您提供的代码,其中包含了问题所在:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import // ...省略了其他导入

public class ShoppingCartSystem extends Application
{
    public static void main(String[] args)
    {
        launch(args);
    }

    ArrayList<String> inventoryTitles = new ArrayList<String>();
    ArrayList<Double> inventoryPrices = new ArrayList<Double>();

    @Override
    public void start(Stage primaryStage)
    {
        // ...(省略了其他部分)

        Button addItemButton = new Button("Add an item");
        addItemButton.setOnAction(event ->
        {
            ObservableList<String> selections =
                    storelist.getSelectionModel().getSelectedItems();

            for (String str : selections)
                cartlist.getItems().addAll(str);

            System.out.println(inventoryTitles);
            System.out.println(inventoryPrices);

        });

        // ...(省略了其他部分)

    }

    private void readBookFile() throws IOException
    {
        String input;  // To hold a line from the file

        // Open the file.
        File file = new File("BookPrices.txt");
        Scanner inFile = new Scanner(file);

        // Read the file.
        while (inFile.hasNext())
        {
            // Read a line.
            input = inFile.nextLine();

            // Tokenize the line.
            String[] tokens = input.split(",");

            // Add the book info to the ArrayLists.
            inventoryTitles.add(tokens[10]); // 这里应该是tokens[0],不是tokens[10]
            inventoryPrices.add(Double.parseDouble(tokens[1])); // 这里应该是tokens[1],不是tokens[10]
        }

        // Close the file.
        inFile.close();

    }

}

问题在于标记化代码中的索引错误。应该使用tokens[0]来获取书籍标题,使用tokens[1]来获取书籍价格。修改这些部分后,标记化应该正常工作,而且ArrayList应该包含正确的数据。

英文:

So I'm working on a school assignment. I have to create a shopping cart system that displays books in a ListView and have buttons/menu items that can add those books to a cart or remove them.

The program is supposed to read a file "BookPrices.txt" and tokenize the strings, separating the words from the digits and then add them to two Arraylists. One Arraylist is for the book titles and the other is for the book prices.

The problem that I'm having is that the tokenizer code doesn't seem to be working. I tested the arraylists with some printlns in the addItemButton to see if there is anything in the arrays and so far they appear empty. Keep in mind the tokenizer code was given to me from the textbook and the full program is still missing code for manipulating data and calculating a total cost.

Assignment:
Create an application that works like a shopping cart system for an online book store.
When your application being execution, it should read the contents of the file and store
the book titles in a ListView. The user should be able to select a title from the list
and add it to a "shopping cart", which is simply another ListView control. The application
should have buttonsor menu items that allow the user to remove items from the shopping
cart, clear the shopping cart of all selections, and check out. When the user checks out,
the application should calculate and display the subtotal of all the books in the shopping
cart, the sales tax (which is 7 percent of the subtotal), and the total.

BookPrices.txt:

I Did It Your Way,11.95
The History of Scotland,14.50
Learn Calculus in One Day,29.95
Feel the Stress,18.50
Great Poems,12.95
Europe on a Shoestring,10.95
The Life of Mozart,14.50

Code:

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.Button;
import javafx.scene.control.MenuBar;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class ShoppingCartSystem extends Application
{
public static void main(String[] args)
{
launch(args);
}
ArrayList<String> inventoryTitles = new ArrayList<String>();
ArrayList<Double> inventoryPrices = new ArrayList<Double>();
@Override
public void start(Stage primaryStage)
{
Label myLabel = new Label("Select books to purchase.");
Label subTotalLabel = new Label("Checkout:");
Label taxLabel = new Label("Checkout:");
Label cartTotalLabel = new Label("Checkout:");
// test inventoryTitles.add("Bob");
ObservableList<String> titleList = FXCollections.observableArrayList(inventoryTitles);
ListView<String> storelist = new ListView<>(titleList);
storelist.setPrefSize(170,170);
storelist.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
//storelist.getItems().addAll(titleList);
//storelist.getItems().addAll("I Did it Your Way: $11.95", "The History of Scotland: $14.50",
//	    "Learn Calculus in One Day: $29.95", "Feel the Stress: $18.50", "Great Poems: $12.95",
//	    "Europe on a Shoestring: $10.95", "The Life of Mozart: $14.50");
ListView<String> cartlist = new ListView<>();
cartlist.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
cartlist.setPrefSize(170,170);
Button addItemButton = new Button("Add an item");
addItemButton.setOnAction(event ->
{
ObservableList<String> selections =
storelist.getSelectionModel().getSelectedItems();
for (String str : selections)
cartlist.getItems().addAll(str);
System.out.println(inventoryTitles);
System.out.println(inventoryPrices);
});
Button removeItemButton = new Button("Remove an item");
removeItemButton.setOnAction(event ->
{
ObservableList<String> selections2 =
cartlist.getSelectionModel().getSelectedItems();
cartlist.getItems().removeAll(selections2);
});
Button clearCartButton = new Button("Clear Cart");
clearCartButton.setOnAction(event ->
{
cartlist.getItems().setAll();	
});
Button checkoutButton = new Button("Check Out");
checkoutButton.setOnAction(event ->
{
//Check out code, maths
final double Tax_Rate = 0.07;
//Int Sales Tax = Subtotal * 7;
//Final total = Sales Tax + Total;
//checkoutLabel.setText("Subtotal, Sales Tax, Total");
});
VBox vbox = new VBox(10, storelist, cartlist, addItemButton, 
removeItemButton, clearCartButton, checkoutButton);
vbox.setAlignment(Pos.CENTER);    
Scene scene = new Scene(vbox, 800, 800);
primaryStage.setScene(scene);
primaryStage.setTitle("Online Bookstore");
primaryStage.show();
}
private void readBookFile() throws IOException
{
String input;  // To hold a line from the file
// Open the file.
File file = new File("BookPrices.txt");
Scanner inFile = new Scanner(file);
// Read the file.
while (inFile.hasNext())
{
// Read a line.
input = inFile.nextLine();
// Tokenize the line.
String[] tokens = input.split(",");
// Add the book info to the ArrayLists.
inventoryTitles.add(tokens[10]);
inventoryPrices.add(Double.parseDouble(tokens[1]));
}
// Close the file.
inFile.close();
}
}

The problem that I'm having is that the tokenizer code doesn't seem to be working. I tested the arraylists with some printlns in the addItemButton to see if there is anything in the arrays, and so far they appear empty. Keep in mind the tokenizer code was given to me from the textbook and the full program is still missing code for manipulating data and calculating a total cost.

答案1

得分: 1

根据你的代码,这是我观察到的:

  • 在应用程序中没有调用你的 readBookFile() 方法。我认为你需要在 start() 方法的第一行先调用这个方法。
  • 如果你的文件位于相同的包中,那么文件对象的初始化有些问题。目前它引用了项目根目录的位置。如果你的文件在同一个包中,我建议使用 Path API。
  • 最后,在加载第一个字符串时存在拼写错误。它被写成了 tokens[10],而不是 tokens[0]

一旦你纠正了这三个问题,你的代码就可以工作了。

英文:

From your code this is what I observed:

  • There is no call to your readBookFile() method in application. I believe you need to first call the method at the first line of your start() method.
  • The initialization of File object is a bit problematic if your file is in the same package. Currently it refers to the project root location. If your file is in the same package, I would suggest to use the Path API.
  • Finally there is a typo error in loading the first string. It is mentioned as tokens[10] instead of tokens[0]

Once your correct all these three, then your code works.
Java/JavaFX – 购物车系统 – 将数据标记为 ArrayList

private void readBookFile() {
String input;  // To hold a line from the file
// Open the file.
Scanner inFile = null;
try {
Path p = Paths.get(getClass().getResource("BookPrices.txt").toURI());
inFile = new Scanner(p.toFile());
} catch (URISyntaxException | FileNotFoundException e) {
throw new RuntimeException(e);
}
// Read the file.
while (inFile.hasNext()) {
// Read a line.
input = inFile.nextLine();
// Tokenize the line.
String[] tokens = input.split(",");
// Add the book info to the ArrayLists.
inventoryTitles.add(tokens[0]);
inventoryPrices.add(Double.parseDouble(tokens[1]));
}
// Close the file.
inFile.close();
}

huangapple
  • 本文由 发表于 2023年7月18日 05:56:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708322.html
匿名

发表评论

匿名网友

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

确定