【问题标题】:Need a programs that asks user to enter 2 integers, check to see if 2nd number is multiple of first number需要一个要求用户输入 2 个整数的程序,检查第二个数字是否是第一个数字的倍数
【发布时间】:2015-10-25 05:07:54
【问题描述】:

我无法弄清楚为什么我的 if-else 语句不能正常工作。这是我目前所拥有的:

import java.util.Scanner;
public class multiple {
   public static void main (String[] args){
        Scanner input = new Scanner (System.in);
        int x = 4;
        int y = 3;
        int multiple = y % x;
        while (multiple != 0){
            System.out.println("Enter two integers: ");
            x = input.nextInt();
            y = input.nextInt();
            if (multiple != 0)
                System.out.println("Oops, sorry! The second integer is NOT a multiple of the first integer.");
            else
                System.out.println("Good Job! " + y + " is a multiple of " + x + "!");
        }       
    }
}

【问题讨论】:

    标签: java if-statement modulo


    【解决方案1】:

    在接受用户输入后,您没有更新multiple。像这样更改您的代码。它应该可以工作。

    import java.util.Scanner;
    public class multiple {
    public static void main (String[] args){
        Scanner input = new Scanner (System.in);
        int x = 4;
        int y = 3;
        int multiple = y % x;
        while (multiple != 0){
    System.out.println("Enter two integers: ");
        x = input.nextInt();
        y = input.nextInt();
       multiple = y % x;
            if (multiple != 0)
                System.out.println("Oops, sorry! The second integer is NOT a multiple of the first integer.");
            else
                System.out.println("Good Job! " + y + " is a multiple of " + x + "!");
        }       
    }
    
    }
    

    【讨论】:

    • 好的,这就是在“while”语句之后重复变量更改以继续循环的意思?
    • 是的似乎是这样。对于每个输入集,您需要计算和重置变量multiple
    • 我一直在阅读,但没有重复正确的代码声明。谢谢
    【解决方案2】:

    您必须在每次更改 x 和 y 时更新您的多重变量。你现在检查 4%3 是否为 0,每一次。

    换句话说,在更新 x 和 y 后将倍数设置为 y%x。

    【讨论】:

    • 那我不会丢失我的 while 语句吗?我需要它不断重复,直到用户输入 2 个整数倍数
    【解决方案3】:

    要补充 Prince 和 playitright 所说的内容,我会要求

    1. 检查用户输入的数字是否不为零。这非常重要,否则您可能会遇到运行时异常。
    2. 您正在尝试 y%x 而不是 x%y。

    因为你选择的数据类型都是int,所以x%y也要勾选。

    假设,

    x=3 和 y=6,您的解决方案有效,但如果我们只是反转 x=6 和 y=3 的值,则输出不正确。

    【讨论】:

    • 如果我希望将第二个整数作为第一个整数的倍数进行测试,我不会将其保留为“Y%X”吗??
    • 如果用户输入 6 & 3,则 3 是 6 ( 6 X 0.5 ) = 3 的倍数,但如果您只考虑整数,那么我认为只需要不等于 0。
    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 2017-02-13
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2022-01-17
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多