java - 有没有办法将这两个 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 语句,同时保持代码按当前方式工作。提前谢谢了!
解决方案
逻辑和行为都是相同的,因此您不必使用两个条件来编写逻辑,您可以将以下代码用作单一方式。
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);
}
推荐阅读
- react-native - React Native codeigniter api无法从axios / async await读取数据
- delphi - 如何为`TBitBtn`设置`ElevationRequired`
- r - 如何更有效地大写列名?
- aws-lambda - API 网关:无法在映射模板中提取原始正文
- flutter - Flutter:为什么默认填充是 8.0?
- javascript - Twitch API 返回不正确的频道
- python - 当列为空时,使用 Strip 的 Pandas 中的属性错误
- java - 记录大 if(.. || ..) 语句的真实条件
- r - 按照官方的“韩文罗马化修订”罗马化韩文字母
- angular - 对 Angular 进行排序的嵌套表是否存在一般问题?