Farid Mammadzada
Farid Mammadzada

Reputation: 11

How to fix the problem with If statement used 3 times?

The task is this - Print "Positive", "Negative" or "Zero" depending on the value of n. I can write the positive and negative part with if, but not the last "zero" part. If I write 0 and then press spacebar, "zero" is shown. But If I write only 0, it gives me error.

import java.util.Scanner; 

public class Main {
    public static void main(String[] args) { 
        Scanner sc= new Scanner(System.in); 
        int n = sc.nextInt(); 
        if (n>0) {
            System.out.println("Positive");
        } else if (n<0) {
            System.out.println("Negative");
        } else if (n == 0); {
            System.out.println("Zero");
        }
        sc.close();
    } 
}

Upvotes: 1

Views: 34

Answers (1)

giusti
giusti

Reputation: 3538

There's an extra semicolon in you code

// ...
} else if (n == 0); {  // <---- HERE
    System.out.println("Zero");
}

This means the block of code is not dependent on the if. In fact, the if is trying to run an empty statement.

Remove the semicolon or just remove the condition altogether. After all, if an integer is neither less than, nor greater than zero, it must be zero.

import java.util.Scanner; 

public class Main {
    public static void main(String[] args) { 
        Scanner sc= new Scanner(System.in); 
        int n = sc.nextInt(); 
        if (n>0) {
            System.out.println("Positive");
        } else if (n<0) {
            System.out.println("Negative");
        } else {
            System.out.println("Zero");
        }
        sc.close();
    } 
}

Upvotes: 2

Related Questions