Reputation: 97
I'm having trouble coding a simple task for loop. What I need for the loop to do is as follows:
1) Prompt the user asking what's 50 + 10 =
2) If the user enters the wrong answer a warning message will pop up saying they have 2 more attempts
3) Once the user exhausts all of their attempts a different message will pop up saying you have no more attempts
This is what I have been able to come up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int attempt = 1;
int answer = 60;
for( attempt = 1; attempt < 0; --attempt)
System.out.print(" 50 + 10 = ");
answer = input.nextInt();
input.nextLine();
if( answer != 60)
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left! ", attempt);
System.out.print( "\n50 + 10 = " );
answer = input.nextInt();
}
if( attempt == 0)
{
System.out.print( "Sorry! You have no more attempts left!" );
}
System.exit(0);
}
If I change the value of the control variable from 1 to say 2 it'll print 50 + 10 = 50 + 10 =
And when I run the program it'll output with 0 attempts left rather than 2 attempts, then 1, then Sorry message.
Upvotes: 0
Views: 131
Reputation: 8101
Have a look here...I have modified it to some extent...
for( attempt = 1; attempt >= 0; --attempt)
{
System.out.print(" 50 + 10 = ");
answer = input.nextInt();
input.nextLine();
if( answer != 60)
{
if(attempt!=0)
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
continue;
}
else
System.out.print( "Sorry! You have no more attempts left!" );
}
System.exit(0);
}
Upvotes: 1