# Beginner Question--Sum of numbers program; Validation

• February 10th, 2014, 01:45 AM
javanightmare
Beginner Question--Sum of numbers program; Validation
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:

Code :

```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."); } }```
• February 10th, 2014, 05:19 AM
GregBrannon
Re: Beginner Question--Sum of numbers program; Validation
Something like (change to fit your variables):
Code java:

```while ( numberEntered < 0 ) { System.out.print( "Enter a non-negative integer!" ); numberEntered = Integer.parseInt(input.nextLine()); System.out.println(); }```
• February 13th, 2014, 08:56 PM
Junky
Re: Beginner Question--Sum of numbers program; Validation
I think you are misunderstanding the requirements. You need to validate user input before you can perform the sum. So you will need 2 loops, one for each task.