简体   繁体   中英

How to check if integer is positive or negative in a WHILE loop in Java?

I need to write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to N, where N is a positive integer number inputted by the user. The program should

  1. Use the While loop;

  2. Check the user's input, and ask the user re-input a valid value if N is not a positive integer number;

  3. Computer and display the average of 1,2,3,...,to N;

  4. Display the output with one decimal number.

I have created the loop correctly, however, I am unable to figure out how to check if the integer is positive or negative. I am new to Java so any help would be greatly appreciated!

Here is my code so far:

import java.util.Scanner; 

public class SumAndAverage {

    public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    System.out.println("*********");
    System.out.println();
    System.out.print("Please input a positive integer number: ");

    int N = keyboard.nextInt(); 

    int i = 1 ;

    int sum = 0;

    while(i <= N)
    {
        sum += i;
        i++;
    }

    System.out.println();
    System.out.println("The sum from 1 to " + N + " is: " + sum);
    System.out.println();
    System.out.printf("The average is: %d%n", sum/N);
    System.out.println();
    System.out.println("*********"); 

        keyboard.close();
    }
}

To check if the var N is negative or positive just use the code below:

if(n < 0){
  System.out.println("Wrong value, please write a positive integer");
} else{
   PROGRAM
}

I hope this help you

A do-while loop can do this job.

int N;
do {
    N = keyboard.nextInt();
}
while (N < 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM