Issue
I'm facing an error when I am doing "do while" loop in Java. Where is the mistake? I don't understand what to do now.
public class JavaBasics{
public static void main(String args[]){
int number;
int choice;
int evensum;
int oddsum;
do {Scanner sc = new Scanner(System.in);
number = sc.nextInt();
if ( number % 2==0 ) {
evensum += number ;
} else {
oddsum += number;
}
System.out.println(" do you want to continue ? if yes enter 1 , if no , enter 0 ");
choice = sc.nextInt;
}
while ( choice == 1 ) {
System.out.println("sum of even numbers " + evensum);
System.out.println("sum of odd numbers" + oddsum);
}
}
}
error: ';' expected
while ( choice == 1) {
^
1 error
error: compilation failed
I think there is a problem in syntax of while because it is showing error in the while statement. Please check it once. The question that I was doing is "to calculate the sum of even and odd integers."
Solution
The correct syntax of a do-while is:
do {
// ...
} while (condition);
The correct syntax of a while is:
while (condition) {
// ...
}
Your code is
do {
// ...
} while (condition) {
// ...
}
Either you wanted a while, and you should remove the do
(and optionally remove the block around the code), or you wanted a do-while (most likely given your code), and you should remove the block statement after the while
and replace it with a ;
, or you wanted a do-while and a while, in which case you need to add a while (condition);
immediately after the do-block.
Answered By - Mark Rotteveel
Answer Checked By - Terry (JavaFixing Volunteer)