Hi,
I'm just starting to learn Java, and I'm trying to write a program to sum integers from 1 to the entered number. The integer entered has to be greater than 0, and I need to use a while statement to validate the input. I also need to use a scanner class for keyboard input.
I have the program able to recognize a negative or zero number, but I cannot figure out how to both sum the numbers and watch the input to make sure it's not negative. Can someone point me in the right direction? I've been working on this thing for more than 6 hours already..
This is my code so far:
import java.util.Scanner; public class SumOfNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a positive nonzero number: "); int x = Integer.parseInt(input.nextLine()); int y = 0; int sum = 0; while (y <= x) { sum = sum + y; y++; System.out.println("Sum of all the integers from 1 through " + x + " is: " + sum); } if (y > x) System.out.println("Invalid. Please enter a positive nonzero number."); } }