1

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();
    }
}
1
  • 2
    it's negative if it's value is less than zero. quite an easy check Commented May 22, 2020 at 7:36

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

A do-while loop can do this job.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.