Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Conditional Statement Exercises: Check the number is negative, zero, or positive

Java Conditional Statement: Exercise-27 with Solution

Write a Java program that reads an integer and check whether it is negative, zero, or positive.

Test Data
Input a number: 7

Pictorial Presentation:

Java conditional statement Exercises: Check the number is negative, zero, or positive

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise27 {
 public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input a number: ");
        int n = in.nextInt();

        if (n > 0)
        {
            System.out.println("Number is positive");
        }
        else if (n < 0)
        {
            System.out.println("Number is negative");
        }
        else
        {
            System.out.println("Number is zero");
        }
    }
}

Sample Output:

Input a number: 7                                                                                             
Number is positive

Flowchart:

Flowchart: Java Conditional Statement Exercises - Check the number is negative, zero, or positive

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to display the following character rhombus structure.
Next: Write a Java program that reads a floating-point number. If the number is zero it prints "zero", otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe