Philip Drach Philip Drach - 6 months ago 16
Java Question

How can I represent a boolean type as it's relative integer?

I am practicing my Java and working on a program that will sum up all of the integers from 1 to 999 that are either a multiple of 3 or a multiple of 5.

Here is what I've written so far:

public class MultiplesOfThreeAndFive {

public static void main(String[] args) {
//For a number to be a multiple, i % number equals 0.
MultiplesOfThreeAndFive m = new MultiplesOfThreeAndFive();
for (int i = 1; i < 1000; i++){
System.out.println(m.checkIfMult(i));
}
}

public boolean checkIfMult(int i){
return (i % 3 == 0 || i % 5 == 0);
}
}


Now when I compile this, all I get is true and false for each number from 1 to 999. I understand that this is because my method return type for my

checkIfMult


method is boolean.

I can't sum up true and false so I want to only acquire those numbers that display as true in the list.

EDIT:

Going by what Tom said...I added this to my main method:

public static void main(String[] args) {
//For a number to be a multiple, i % number equals 0.
MultiplesOfThreeAndFive m = new MultiplesOfThreeAndFive();
for (int i = 1; i < 1000; i++){
System.out.println(m.checkIfMult(i));
if (m.checkIfMult(i) == true){
}
}
}

Answer

You can keep a running sum like this:

public class MultiplesOfThreeAndFive {

    public static void main(String[] args) {
        //For a number to be a multiple, i % number equals 0.
        MultiplesOfThreeAndFive m = new MultiplesOfThreeAndFive();

        int sum = 0;
        for (int i = 1; i < 1000; i++){
            if (m.checkIfMult(i))
            {
                sum = sum + i;
            }
        }
        System.out.println("Sum is: " + sum);
    }

    public boolean checkIfMult(int i){
        return (i % 3 == 0 || i % 5 == 0);
    }
}

Side Note: You can make the checkIfMult method static in this example. If you do so, then you don't need to create an instance of the MultiplesOfThreeAndFive class.