java - 浮点乘法错误并在 GUI 中显示

标签 java jframe

我正在开展一个学校项目,其中从文件中读取价目表,将其作为对象存储在数据库中,然后读取购物 list 、计算总计并在 GUI 中显示,但没有显示正确的是,我得到的每件商品的成本全为零,我已附加代码如下:

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

import javax.swing.*;


public class Project1 {

public static void main(String[] args) throws FileNotFoundException {
    String input = JOptionPane.showInputDialog("Please enter the filename of your shopping list:"); //Prompt user to enter filename

    Database base = new Database(); //Create Database
    File file = new File(input);    //Create File object
    Scanner in = new Scanner(file); //Create Scanner object
    float total = 0;                //float to hold sum of grocery list
    String list = "";               //String to create receipt
    float a = 0;                    //float to hold total of each individual item

    /*This while loop will run as long as the File object has a next line. It will tokenize the line from 
     * the file, append to the string the number, and name, create a running total for the grocery list, 
     * and append the string with the cost per item.
     */
    StringTokenizer tokenizer;

    while(in.hasNextLine()){

        input = in.nextLine();                                      //Read the next line from the file
        tokenizer = new StringTokenizer(input, ",");                //Create Tokenizer object with line from file
        input = tokenizer.nextToken();                              //Get first token (Object number)
        list += (input + "  " + base.getName(input) + " ");
        input = tokenizer.nextToken();
        a = Float.parseFloat(input);
        total += a;
        a = a * (base.getPrice(input));
        list += ("$" + a + "\n");
    }
    in.close();

    JFrameBuild frame = new JFrameBuild(list, total);

}
}

下一个类:

import java.io.*;
import java.util.*;
/**
 * The Database class will process a .txt file to tokenize the contents and assemble an array of objects.
 * @author Andrew
 *
 */

public class Database {
ProduceItem[] array = new ProduceItem[16];  //Create String array

public Database() throws FileNotFoundException{
    String name = "PriceList.txt";
    File file = new File(name); //Create file object
    int i = 0;


    Scanner inputFile = new Scanner(file);  //Create Scanner object to read from file
    String line = null; //String for input

    while(inputFile.hasNextLine()){                                     //While loop to sort through the file
            array[i] = new ProduceItem();                               //Initalize object
            line = inputFile.nextLine();                                //Read line from file
            StringTokenizer tokenizer = new StringTokenizer(line, ","); //Tokenize the line
            array[i].setCode(tokenizer.nextToken());                    //Set the ID code for the object
            array[i].setName(tokenizer.nextToken());                    //Set the name for the object
            array[i].setPrice(Float.parseFloat(tokenizer.nextToken())); //Set the price for the object
            i++;                                                        //increment the counter
    }   
    inputFile.close();
}
/**
 * This method will sort the array of objects and return the name of the ProduceItem with the matching 
 * ID code.
 * 
 * @param code The code of the ProduceItem we need the name of
 * @return  Returns the name of the ProduceItem
 */
public String getName(String code){
    String name = "";                                                   //Initalize the name String

    for(int i = 0; i < array.length; i++){                              //For loop to sort the array
        if(code.equals(array[i].getCode())){
            name = array[i].getName();
            break;                                                      //Break the loop
        }
    }
    return name;
}
/**
 * This method sorts the array and returns the price of the object.
 * 
 * @param code The code of the object we need to price
 * @return Returns the price of the said object per pound
 */
public float getPrice(String code){
    float price = 0F;

    for(int i = 0; i < array.length; i++){
        if(code.equals(array[i].getName())){
            price = array[i].getPrice();
            break;
        }
    }
    return price;


}

}

下一个类:

import java.awt.*;
import javax.swing.*;


public class JFrameBuild {

public JFrameBuild(String line, float total){
    //Create and set up the window.
    JFrame frame = new JFrame("Shopping Receipt");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize( 300,300);//width, height);
    frame.setLocation(200,100);//x, y);
    frame.setLayout(new GridLayout(2,1));

    JTextArea textArea = new JTextArea(25, 25);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.getContentPane().add(scrollPane);
    JLabel label = new JLabel("Shopping total is:  $" + total);
    frame.getContentPane().add(label);

    textArea.setText(line);

    //Display the window.
    frame.pack();
    frame.setVisible(true);



}

}

下一个类:

/** * ProduceItem 类创建农产品对象及其相应的数据。 * @作者安德鲁 * */ 公共(public)类 ProduceItem {

private String code;
private String name;
private float price;
/**
 * Standard constructor for the ProduceItem class
 * @param code  Code of the ProduceItem object
 * @param name  Name of the ProduceItem object
 * @param price Price of the ProduceItem object
 */
public ProduceItem(String code, String name, float price){
    this.code = code;
    this.name = name;
    this.price = price;

}
/**
 * NO Arg constructor for the ProduceItem class
 */
public ProduceItem(){
    //No Arg constructor
}
/**
 * Accessor method for code variable
 * @return the code for the item
 */
public String getCode(){
    return code;
}
/**
 * Accessor method for the name variable
 * @return  the name for the item
 */
public String getName(){
    return name;
}
/**
 * Accessor method for the price variable
 * @return the price of the item
 */
public float getPrice(){
    return price;
}
/**
 * Mutator method for the code variable
 * @param code The code for the item
 */
public void setCode(String code){
    this.code = code;
}
/**
 * Mutator method for the name variable
 * @param name The name of the item
 */
public void setName(String name){
    this.name = name;
}
/**
 * Mutator method for the price variable
 * @param price The price of the item
 */
public void setPrice(float price){
    this.price = price;
}

}

以下是txt数据: 价目表:

4019,APPLES,0.99
4218,APRICOTS,3.49
4771,AVOCADOS,2.59
4011,BANANAS,.69
4045,CHERRIES,4.99
4263,DATES,3.99
4027,GRAPEFRUIT,1.09
4637,GRAPES,2.76
4053,LEMONS,3.45
4319,MELON,1.99
4377,NECTARINE,3.69
4012,ORANGES,2.49
4037,PEACHES,2.99
4026,PEARS,1.99
4029,PINEAPPLE,2.59
4041,PLUMS,3.49

购物 list :

4012,4.03
4019,2.3
4011,1.72
4029,1.7
4027,2.37
4037,2.99
4637,2.01
4053,0.56
4319,5.65
4026,0.99
4041,0.49

感谢任何帮助!

最佳答案

由于您分割行的方式,您实际上是将“数量”值传递到 getPrice 方法中

input = in.nextLine();                                      //Read the next line from the file
tokenizer = new StringTokenizer(input, ",");                //Create Tokenizer object with line from file
input = tokenizer.nextToken();                              //Get first token (Object number)
list += (input + "  " + base.getName(input) + " ");
// And input is now the "quanity", not the code...
input = tokenizer.nextToken();
a = Float.parseFloat(input);
total += a;
a = a * (base.getPrice(input));
list += ("$" + a + "\n");

然后在您的 getPrice 方法中,您将“代码”与产品名称进行比较...

if (code.equals(array[i].getName())) {

这永远不会是true。相反,您应该使用 getCode

if (code.equals(array[i].getCode())) {

为了简单起见(以及其他原因),我已经在 StringTokenizer 上使用了 String#split,您还应该避免循环内的 String 连接, 在那里你可以。就您而言,这不是一笔“大规模”交易,但您应该尽可能养成良好的习惯。

相反,您应该使用 StringBuilder,例如...

StringBuilder list = new StringBuilder(64);
while (in.hasNextLine()) {

    input = in.nextLine();                                      //Read the next line from the file
    String[] tokens = input.split(",");
    String code = tokens[0];
    String quanity = tokens[1];
    list.append(code).append("  ").append(base.getName(code)).append(" ");
    a = Float.parseFloat(quanity);
    total += a;
    a = a * (base.getPrice(code));
    list.append("$").append(a).append("\n");
}
in.close();

JFrameBuild frame = new JFrameBuild(list.toString(), total);

速度更快,内存占用更少。

它还可以查看 The try-with-resources Statement更好地处理您的资源,因为它将确保您的资源在发生错误或不发生错误时正确关闭

关于java - 浮点乘法错误并在 GUI 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271867/

相关文章:

java - 如何将带有 2DGraphics 的 JPanel 放在 JFrame 上(同一类)

java - 无法在 jbpm 6.1.0 中运行包含预定义电子邮件服务任务的进程

java - tomcat 应用程序服务器中的内存缓存?

JavaFX listView int[] 类型的拖动列表项(Java Messsge :-1 )

Java Jframe 导出时未打开

java - 如何停止关闭 JFrame 窗体?

java - 用于激发 StructType 的 Avro Schema

java - 在 JFrame 中将图像绘制到 JPanel

java - 传递在一个 JFrame 的文本字段中输入的值作为另一个 JFrame 的输入参数

java - 在 GUI 中显示对象数组