1

I am supposed to write a program that asks the user for 5 non-negative integers and then displays the sum of these integers. Also if the user enters a non-integer value, I have to keep asking until the user has inputted 5 acceptable values.

How do I do this using non-nested for statements?? Thanks!!!

Clarisa
  • 125
  • 2
  • 12
  • 1
    Normally this sort of thing is done with a while-loop, not a for-loop. In either case, why would you need to nest loops at all? – azurefrog Mar 03 '15 at 20:52
  • possible duplicate of [Check user input and for loop](http://stackoverflow.com/questions/27779016/check-user-input-and-for-loop) – Stephen P Mar 03 '15 at 22:02

2 Answers2

1

This should work for you. It continues to scan until the user has typed an integer.

    Scanner scan = new Scanner(System.in);
    int sum = 0;

    for(int i = 0; i < 5; i++)
    {

    System.out.println("Enter integer value: ");
    while (!scan.hasNextInt())
    {
        System.out.println("That's not a number, try again: ");
        scan.next();
    }
    sum += scan.nextInt();
    }
    System.out.println(sum);
Jud
  • 1,324
  • 3
  • 24
  • 47
  • The OP asked for a non-nested solution. Also, it's generally a good idea when rejecting a user input to display a reason why and prompt them again. – azurefrog Mar 03 '15 at 21:07
  • 1
    @azurefrog I assumed when he said "non-nested for statements" he meant he doesn't want a for loop inside another for loop. And yes, I agree. I will edit the code to re-prompt. – Jud Mar 03 '15 at 21:09
1

Use a while() loop.

int sentinel = 0;
Scanner s = new Scanner(System.in);
int sum = 0;

while (sentinel < 5 && s.hasNextInt()){
  int num = s.nextInt();
  if(num>=0){
    sum += num;
    sentinel++;
  }else
    System.out.println("That wasn't a non-negative int :(");
}

And then just print out the sum.

Remption
  • 220
  • 1
  • 7