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
Use the While loop;
Check the user’s input, and ask the user re-input a valid value if N is not a positive integer number;
Computer and display the average of 1,2,3,...,to N;
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();
}
}