如何将判断整数整除性的Java布尔输出代码改写为if语句?
用if语句实现整数整除判断的布尔输出
没问题!刚入门编程的时候确实会对把布尔表达式转成if语句有点困惑,我来给你展示怎么用if语句实现和你原来代码完全一样的功能,逻辑更直观,结果也完全一致~
首先,你原来的代码是直接把布尔表达式拼接到输出语句里,现在我们可以通过定义布尔变量+if-else赋值的方式,或者直接在if语句里打印结果,两种方式都能达到目的。
完整实现代码
package truefalse1; import java.util.Scanner; public class Truefalse1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your integer: "); int number = input.nextInt(); // 判断是否能同时被5和6整除 boolean divisibleByBoth = false; if (number % 5 == 0 && number % 6 == 0) { divisibleByBoth = true; } System.out.println("Is the number divisible by 5 and 6? " + divisibleByBoth); // 判断是否能被5或6整除 boolean divisibleByEither = false; if (number % 5 == 0 || number % 6 == 0) { divisibleByEither = true; } System.out.println("Is the number divisible by 5 or 6? " + divisibleByEither); // 判断是否能被其中一个整除但不同时被两者整除(异或逻辑) boolean divisibleByOneNotBoth = false; // 两种互斥情况:能被5整除但不能被6,或者能被6整除但不能被5 if ((number % 5 == 0 && number % 6 != 0) || (number % 6 == 0 && number % 5 != 0)) { divisibleByOneNotBoth = true; } System.out.println("Is the number divisible by 5 or 6, but not both? " + divisibleByOneNotBoth); input.close(); // 记得关闭Scanner资源哦 } }
代码解释
- 第一个判断:我们先初始化
divisibleByBoth为false,如果输入的整数同时满足被5和6整除的条件,就把变量设为true,最后输出这个变量,和你原来用((number % 5 == 0) && (number % 6 == 0))的结果完全一致。 - 第二个判断:同理,只要整数能被5或6中的任意一个整除,就把
divisibleByEither设为true,对应原来的||逻辑。 - 第三个判断:这是异或逻辑(原来的
^运算符),我们拆解成两种互斥的情况:能被5整除但不能被6,或者能被6整除但不能被5,只要满足其中一种,就把divisibleByOneNotBoth设为true,和原来的异或效果完全相同。
简化写法(直接打印)
如果你不想用变量,也可以直接在if-else里打印true或false,比如:
// 直接打印是否同时被5和6整除 System.out.print("Is the number divisible by 5 and 6? "); if (number % 5 == 0 && number % 6 == 0) { System.out.println(true); } else { System.out.println(false); }
这种写法更直接,同样能实现需求,看你个人习惯选择就好。
内容的提问来源于stack exchange,提问作者F D
相关产品推荐
相关产品推荐

