Test if a number is a multiple of another [closed]

拈花ヽ惹草 提交于 2021-02-17 07:16:27

问题


i have a question in my textbook that says:

Write a method multiple that takes two integers as its arguments and returns true if the first integer is divisible evenly by the second one (i.e., there is no remainder after division); otherwise, the method should return false. Incorporate this method into an application that enables the user to enter values to test the method.

and i wrote this code but its not working:

public class project1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a, b;
        System.out.println("enter the first number");
        a = input.nextInt();

        System.out.println("enter the first number");
        b = input.nextInt();
    }

    public static boolean multiple(int g, int c) {

        int g, c;

        if (g % c = 0) {
            return true;
        } else {
            return false;

        };
    }
}

回答1:


First of all you don't need to declare g and c again in the function multiple (It is an error). Second, you didn't call the function at all, you just implemented it. And like other people answered, you need to have == instead of =.

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    int a,b;
    System.out.println("enter the first number");
    a=input.nextInt(); 

    System.out.println("enter the first number");
    b=input.nextInt();

    boolean result = multiple(a,b);
    System.out.println(result);
}

public static boolean multiple (int g,int c){
    if (g%c==0){
        return true;
    }
    else
    {
        return false;
    }
}

Note that you can have a shorter version of multiple which have only one line: return g%c==0;




回答2:


//int g, c;
^^

Remove this line..


if (g%c==0){
        ^

You need to use == for checking equality.


You can actually do the below to cut down few lines as well..

public static boolean multiple(int g, int c) {
    return g%c == 0;
}



回答3:


There are too many errors in your method. It actually should be like this:

public static boolean multiple(int g, int c) {
    return g % c == 0;
}



回答4:


You're declaring the variables twice besides the = issue. Try this:

public static boolean multiple(int g, int c) {
    return g % c == 0;
}


来源:https://stackoverflow.com/questions/14474267/test-if-a-number-is-a-multiple-of-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!