gpt4 book ai didi

java - Java初学者,在最后一个if-else语句中,我只是无法弄清楚 "but not both "部分

转载 作者:行者123 更新时间:2023-12-01 21:15:38 24 4
gpt4 key购买 nike

import java.util.*;
public class Divisible {

public static void main(String[] args) {
// Divisible by 5 and 6 or not
Scanner s = new Scanner(System.in);
int x;
System.out.print("Enter an integer: ");
x = s.nextInt();
if ((x % 5==0) && (x % 6==0)){
System.out.print("is "+x+" divisible by 5 and 6? ");
System.out.print("true");
}else{
System.out.print("is "+x+" divisible by 5 and 6? ");
System.out.print("false");
}// Divisible by 5 or 6
if ((x % 5==0) || (x % 6==0)){
System.out.print("\nIs "+x+" divisible by 5 or 6? ");
System.out.print("true");
}else{
System.out.print("Is "+x+" divisible by 5 or 6? ");
System.out.print("false");
}// Divisible by 5 or 6,but not both
if ((x % 5==0) || (x % 6==0)){ //here is my problem, i cant figure out the code for "not both" part
System.out.print("Is "+x+" divisible by 5 or 6, but not both? ");
System.out.print("true");
}else{
System.out.print("Is "+x+" divisible by 5 or 6, but not both? ");
System.out.print("false");
}

}
}

我知道我的最后一个 if-else 语句是错误的,我只是无法弄清楚最后一个任务的编码是““+x+”能否被 5 或 6 整除,但不能同时被两者整除?”

谢谢

最佳答案

您可以使用以下逻辑

if(x%5 == 0 && x%6 == 0){
SOP("number is divisible by both 5 and 6);
}else{
if(x%5 == 0){
SOP("Number is divisible only by 5");
}else if(x%6 == 0){
SOP("Number is divisible only by 6");
}else{
SOP("Number is not divisible 5 nor by 6");
}
}

关于java - Java初学者,在最后一个if-else语句中,我只是无法弄清楚 "but not both "部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40233055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com