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

标签 java if-statement

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/

相关文章:

java - keycloak (spring boot) 不验证 REST 端点

java - 无法 Autowiring 。找不到 Neo4jTemplate 类型的 beans

Excel - 如何在 Excel IF 语句中添加单词

你能扭转总数吗? (循环C)

java - 如何格式化 3 个条件的逻辑并使用前一个条件?

java - Axis2在tomcat上运行时不断在temp文件夹中生成文件

java - 循环语句的freemarker模板

java - 反序列化时动态绑定(bind)JsonProperty

php - php if 语句的奇怪问题

r - dplyr 使用 if else 有条件地按组过滤