有没有办法组合这两个if语句?

时间:2018-11-09 15:06:59

标签: java if-statement jframe

我正在做一个个人任务,用户输入生日,然后显示用户的占星符号和符号说明。但是由于所有的占星术迹象都是几个月,所以我将if语句分为多个if语句,例如每个月一个

if (birthMonth == 5 && (21<=birthDay && birthDay <=31)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    else if (birthMonth == 6 && (1<=birthDay && birthDay <=21)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

我想知道是否有一种方法可以组合if语句,同时使代码保持当前状态。提前非常感谢!

2 个答案:

答案 0 :(得分:2)

逻辑和行为都是相同的,因此您不必使用两个条件来编写逻辑,就可以将下面的代码作为一种方式使用。

if (birthMonth == 5 && (21<=birthDay && birthDay <=31) || birthMonth == 6 && (1<=birthDay && birthDay <=21)) {
        JFrame frame = new JFrame();
        String symbol = "Your sign is Gemini. You are cerebral, chatty, love learning and education, charming, and adventurous.   ";
        symbol += bday;
        JLabel label = new JLabel(symbol, new ImageIcon("gemini.jpg"), JLabel.CENTER);
        label.setVerticalTextPosition(SwingConstants.TOP);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

答案 1 :(得分:0)

为什么不使用or运算符|| ?像这样:

(birthMonth == 5 && (21<=birthDay && birthDay <=31) || (birthMonth == 6 & (1<=birthDay && birthDay <=21)))