我試圖減少代碼,使我的一切看起來更乾淨,更好,但我不知道如何更改此代碼,以便功能保持不變,但代碼少。我也是新來的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]。 –