简体   繁体   English

有没有办法将这两个 if 语句结合起来?

[英]Is there a way to combine these two if statements?

I was working on a personal assignment where the user types their birthday, and then it displays the user's astrological sign and a description of the sign.我正在做一个个人作业,用户输入他们的生日,然后显示用户的星座和星座描述。 But since all astrological signs are multiple months, I have split the if statements into multiple if statements, one for each month, for example但是由于所有的星座都是多个月,我将 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);
    }

I was wondering if there is a way to combine the if statements, while keeping the code working the way it currently is.我想知道是否有一种方法可以组合 if 语句,同时保持代码按当前方式工作。 Many thanks in advance!提前谢谢了!

Both logic and behavior are same so you don't have to use two condition to write your logic you can use below code as a single way.逻辑和行为都是相同的,因此您不必使用两个条件来编写逻辑,您可以将下面的代码用作单一方式。

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);
    }

Why don't you use the or operator ||为什么不使用 or 运算符 || ? ? like this:像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM