0
這是我的停車場系統代碼的一部分。我在使用'count'時遇到了一些問題。目前,我的程序爲每個輸入'reg no','high value'和'large vehicle'增加了1個計數。每次我只輸入新的車輛登記號碼時,我希望我的程序只添加1個?我該怎麼做呢?用Java計算我不是很好。這是我到目前爲止:計數車輛數量java
package carpark;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class textBox extends javax.swing.JFrame
implements ActionListener
{ // declare the components and variables
private final JLabel inputLabel,inputLabel2,inputLabel3,countLabel;
private final JTextField inputBox,inputBox2,inputBox3,countBox;
private final JButton enterButton;
private final JButton clearButton;
private int count;
private String sum;
private String inputString, countString;
private String sumString;
public textBox()
{ // sets up the components and places them
this.setLayout(new FlowLayout());
this.inputLabel = new JLabel("Please enter the vehicle's registration number:");
this.inputBox = new JTextField(8);
this.inputLabel2 = new JLabel("Is this a high-value car? Enter yes or no:");
this.inputBox2 = new JTextField(4);
this.inputLabel3 = new JLabel("Is this a large vehicle? Enter yes or no:");
this.inputBox3 = new JTextField(4);
this.countLabel = new JLabel(" Car Count");
this.countBox = new JTextField(3);
this.enterButton = new JButton("Enter");
this.clearButton = new JButton("Clear");
this.add(inputLabel);
this.add(inputBox);
this.add(inputLabel2);
this.add(inputBox2);
this.add(inputLabel3);
this.add(inputBox3);
this.inputBox.addActionListener(this);
this.add(countLabel);
this.add(countBox);
this.countBox.setEditable(false);
this.add(enterButton);
this.enterButton.addActionListener(this);
this.add(clearButton);
this.clearButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{ // reacts to the ENTER key being pressed
if (event.getSource() == this.enterButton || event.getSource() == this.inputBox)
try
{
this.inputString = inputBox.getText();
this.count += 1;
this.countString = Integer.toString(this.count);
this.countBox.setText(this.countString);
}
catch (NumberFormatException entry)
{
this.inputBox.setText("");
}
else if (event.getSource() == this.clearButton)
{
this.inputBox.setText("");
this.countBox.setText("");
this.count = 0;
}
}
}
你需要一個'List'或註冊車輛的'Map',只增加了計數,當你看到一個新的註冊號 – benji 2014-11-22 18:20:25
您不必連接到「高價值」或任何監聽器「大型車輛」文本框,那麼您確定在這些框中輸入的內容會導致您的問題?我建議讓你的'actionPerformed'方法記錄事件(event.toString()'或'event.paramString()');也許計數正在增加一些你不期待的事件。雖然我有點猜測 – ajb 2014-11-22 18:26:04