我试图减少代码,使我的一切看起来更干净,更好,但我不知道如何更改此代码,以便功能保持不变,但代码少。我也是新来的Java,所以如果有适合我的替代方法写有相同的输出这个代码,我将不胜感激,如果有人能告诉我我可以使用相同的结果来减少此代码吗?
static class Action4 implements ActionListener {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = ((JTextField) e.getSource()).getText();
if (name.equals("Test1")) {
name = JOptionPane.showInputDialog("Enter Name ");
String day;
int totalCost;
int visitors;
day = JOptionPane.showInputDialog("Enter what day you'd like to attend ");
visitors = Integer.parseInt(JOptionPane.showInputDialog("Enter how many people are visiting "));
totalCost = visitors * 20;
JOptionPane.showMessageDialog(null, " You are attending the " + name + " On " + day + visitors + " attending " + "total cost " + totalCost);
} else {
if (name.equals("test2")) {
name = JOptionPane.showInputDialog("Enter Name ");
String day;
day = JOptionPane.showInputDialog("Enter what day you'd like to attend ");
int visitors;
visitors = Integer.parseInt(JOptionPane.showInputDialog("Enter how many people are visiting "));
int totalCost;
totalCost = visitors * 17;
JOptionPane.showMessageDialog(null, " You are attending the " + name + " On " + day + visitors + " attending " + "total cost " + totalCost);
} else {
if (name.equals("test3")) {
name = JOptionPane.showInputDialog("Enter Name ");
String day;
day = JOptionPane.showInputDialog("Enter what day you'd like to attend ");
int visitors;
visitors = Integer.parseInt(JOptionPane.showInputDialog("Enter how many people are visiting "));
int totalCost;
totalCost = visitors * 22;
JOptionPane.showMessageDialog(null, " You are attending the " + name + " On " + day + visitors + " attending " + "total cost " + totalCost);
} else {
JOptionPane.showMessageDialog(null, "Wrong input!");
}
}
最明显的变化:使用'else if',而不是'else {if'。 –
这个问题更适合[codereview.se]。 –