# Thread: If Else Statement in While Loop

1. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## If Else Statement in While Loop

Hello,

I'm in a Java programming course for college and can't figure out how to get an if else statement to work in a while loop. The goal is to read some numbers from a text file called data.txt file and split them into even and odds. I'm then supposed to add the even numbers with the evens and the odd numbers with all the other odd numbers then output the result (I know how to output).

Like I said I just can NOT figure out how to use an if else statement in a while loop (supposed to use an EOF loop) to split them up. If there's a better way on how to do this please let me know.

Thanks for any help and if more information is needed to help please say so.

Here's the code I have:
Java Code:
```public static void Problem3(){
int sumeven = 0, sumodd=0;
String even, odd;

try{
Scanner sc = new Scanner(fr);

while (sc.hasNextInt())
{if (sc.nextInt()%2==0);
sumeven+=sumeven;
else
sumodd+=sumodd;}

}//end try
catch (Exception e){
System.out.println(e.getMessage());
}//end catch

}//end of problem 3```

Note: I receive an error from the code "else" saying to delete this token.

2. ## Re: If Else Statement in While Loop

Remove the ; after the if statement... line 10
Last edited by santa; 02-24-2012 at 12:30 AM.

3. Member
Join Date
Feb 2012
Posts
5
Rep Power
0

## Re: If Else Statement in While Loop

Thanks santa. Problem solved.

I still can't believe I overlook small things like that still I've been looking at this code for about 1 hour now trying to figure it out.

4. ## Re: If Else Statement in While Loop

Originally Posted by santa
Remove the ; after the if statement... line 10
Sharp eyes and good catch!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•