首页 > 解决方案 > 有没有办法将这两个 if 语句结合起来?

问题描述

我正在处理一项个人任务,用户输入他们的生日,然后显示用户的星座和星座的描述。但是由于所有的星座都是多个月,我将 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 语句,同时保持代码按当前方式工作。提前谢谢了!

标签: javaif-statementjframe

解决方案


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

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

推荐阅读