# Average Sum of User Input with Try/Catch

Page 1 of 1

## 2 Replies - 4796 Views - Last Post: 21 October 2010 - 12:34 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=196055&amp;s=c6f679c9d64fd4d1eef47a21f3706762&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 newFrau

Reputation: 0
• Posts: 4
• Joined: 26-January 10

# Average Sum of User Input with Try/Catch

Posted 21 October 2010 - 10:20 AM

Hi,

The problem I'm working on asks the user to enter 10 numbers. Then the numbers are summed and averaged. The program must give an appropriate error message when a NumberFormatException is thrown. After the error message is displayed, the program must continue until 10 numbers are entered.

The problem I'm having is getting the 10 numbers if the error is thrown. Because I'm using a counter to control the loop, the program counts the illegal characters as an iteration.

I tried to solve this by using a boolean variable. Currently, my loop will loop one extra time than I need it to if the error is thrown. If I enter a string character once, the program will average 11 numbers. I'm not sure what I'm missing.

Here's the code:

```  public static void main(String[] args) {
String input;
Integer number =0;
Scanner keyboard = new Scanner(System.in);
Integer count = 0;
Integer sum = 0;
Integer average = 0;
Boolean valid = true;

while (count < 10)

{
valid = true;
System.out.println("Enter a number to sum: ");
try{

input = keyboard.nextLine();

number = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.print("Whoops, you didn't enter a number. Please try again. ");
valid = false;
}

sum += number;

if (valid == false)
count--;
else
count++;

}

average = sum/count;

System.out.println("The average is: " + average);
}

}

```

Is This A Good Question/Topic? 0

## Replies To: Average Sum of User Input with Try/Catch

### #2 n8wxs

• --... ...-- -.. . -. ---.. .-- -..- ...

Reputation: 972
• Posts: 3,878
• Joined: 07-January 08

## Re: Average Sum of User Input with Try/Catch

Posted 21 October 2010 - 10:39 AM

The try...catch block already gives you a boolean state. The number conversion either succeeds or it doesn't. So you don't need the valid flag.

Put all of the summing logic in the try{} block. Increment count there as well.

### #3 newFrau

Reputation: 0
• Posts: 4
• Joined: 26-January 10

## Re: Average Sum of User Input with Try/Catch

Posted 21 October 2010 - 12:34 PM

n8wxs, on 21 October 2010 - 09:39 AM, said:

The try...catch block already gives you a boolean state. The number conversion either succeeds or it doesn't. So you don't need the valid flag.

Put all of the summing logic in the try{} block. Increment count there as well.

Thanks for your help. It seems my logic is faulty:)