You are not breaking the outer while loop after successful input by user. So the control after these statements:
c=c+a;
System.out.println("The result is :"+c);
will reach the for
loop again and again. And hence the statement after the for
loop is unreachable, as the loop will now run infinitely.
Add a break
after the outer while loop finishes:
c=c+a;
System.out.println("The result is :"+c);
} // While loop ends
break;
BTW, you are complicating your task too much by having those infinite for
loops. You should read the first number outside the loop
, and then add a while
loop to read more inputs from user:
System.out.print("Please enter a number:");
a=input.nextInt();
while (true) {
System.out.println("Do you want to add more: [y/n]");
ans=input.next().charAt(0);
if (ans == 'n' || ans == 'N') break;
if (ans == 'y' || ans == 'Y') {
System.out.print("Please enter a number:");
int c = input.nextInt();
a += c;
continue;
}
System.out.println("Please enter a valid option: [y/n]");
continue;
}
System.out.println("The result is :"+c);
Apart from that, you should also validate the input whether it's really an integer
, before invoking input.nextInt()
method, which will blow if user passes "abc"
. For that use input.hasNextInt()
method. I leave that task to you.