adplus-dvertising

If Statement Broken

Asked 2 days ago
Viewed 10 times

The first if statement that declares a number divisible by 3 also prints out the integer. The if statement regarding 5 works fine for some reason even though they are both the same.

Output should be 1 2 clip 4 clop etc.

But instead it reads 1 2 clip3 4 clop

I have tried making an explicit if statement to fix the issue but then it removes the numbers entirely

public static class NaturalNumbers1 {
    
    private static Scanner sc;
    public static void main(String[] args) 
    {
        int number, i;
        
        sc = new Scanner(System.in);
        
        System.out.print(" Enter an Integer: ");
        number = sc.nextInt();  
        
        for(i = 1; i <= number; i++){
            if ( i % 3 ==0){
                System.out.print("clip");
            }
            if ( i % 5 ==0){
                System.out.print("clop");
            }
            else 
                System.out.print(i);

            System.out.println("\t"); 
        }   
    }
}

}

asked 2 days ago

Correct Answer

You have two distinct if(s) followed by an else. You need an else before the second if. Like,

if ( i % 3 ==0){
    System.out.print("clip");
}
else if ( i % 5 ==0){
answered 2 days ago