import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
/**
* @author Otacon
*/
public class Price extends JFrame implements ActionListener{
private JLabel disLabel;
private JTextField disField;
private JButton calButton;
public Price(){
super("Enter distance");
disLabel = new JLabel("Enter distance in kilo-meter: ");
disField = new JTextField(20);
disField.addActionListener(this);
calButton = new JButton("Show Price");
calButton.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(disLabel);
this.add(disField);
this.add(calButton);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300,120);
this.setLocation(100,100);
this.setVisible(true);
System.out.println("Program Started");
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == calButton || e.getSource() == disField){
double distanceVal = 0.0;
double priceVal = 0.0;
boolean validDistanceVal = true;
try{
distanceVal = Double.parseDouble(disField.getText().trim());
if(distanceVal <= 0){
validDistanceVal = false;
}
}catch(NumberFormatException ex){
validDistanceVal = false;
}
if(!validDistanceVal){
JOptionPane.showMessageDialog(this, "Wrong distance value.", "Error", JOptionPane.ERROR_MESSAGE);
}else{
priceVal = calPrice(distanceVal);
DecimalFormat df = new DecimalFormat(".00");
JOptionPane.showMessageDialog(this, "Price: " + df.format(priceVal), "The Price", JOptionPane.INFORMATION_MESSAGE);
}
disField.selectAll();
}
}
private double calPrice(double dis){
double retVal = 7.0;
if(dis > 3.0){
int multiplier = 0;
while(dis > 3.0){
multiplier++;
dis -= 1.0;
}
retVal += multiplier*1.8;
}
return retVal;
}
public static void main(String[] args){
new Price();
}
}
上面的哥们写的很好了,给人家加分吧,呵呵!