我正在开展一个学校项目,从文件中读取价格表,作为对象存储在数据库中,然后读取购物清单,计算总数并在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类创建生成对象及其相应的数据。 * @author Andrew * * / 公共类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
ShoppingList:
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
感谢任何帮助!
答案 0 :(得分:1)
由于您分割线的方式,您实际上是将“数量”值传递到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())) {
为了简单起见,我已经使用String#split
而不是StringTokenizer
(除了其他原因),你还应该避免在循环中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以更好地处理您的资源,因为如果发生错误,它将确保您的资源正确关闭