1) The first loop I need to use is a do/while. In this loop the user is prompted to type in a word. If the user types in the wrong word they get an error message:
Invalid! Try Again! 2 attempt(s) left!
Invalid! Try Again! 1 attempt(s) left!
Sorry! You have no more attempts left!
This output works as long as the wrong word is entered each time, but if the correct word is entered after 1 failed attempt it still applies the error message
2) Within my second loop (for loop) the user is asked to enter “3 * 8 = ” This portion of the loop works fine if a wrong number is entered all 3 times or if 24 is entered on any attempt.
The problem lies in the loop after 24 is entered. The output is as follows:
Thank you blah blah. We’ll call you at 5555555555 if you’re a winner. 3 * 8 = Where the 3 * 8 should not be showing. I realize I could enter a break; after this statement, but the instructions specifically say that I cannot use the break command.
The correct output should read: Thank you blah blah. We’ll call you at 5555555555 if you’re a winner.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int attempt = 2;
int answer = 24;
long phoneNumber = 0;
String firstName = "";
String lastName = "";
String wordOfTheDay = "";
System.out.printf("Enter the word of the day: ");
wordOfTheDay = input.nextLine();
if(wordOfTheDay.equals("tired"))
{
for( attempt = 2; attempt >= 0; --attempt)
{
System.out.print(" 3 * 8 = ");
answer = input.nextInt();
input.nextLine();
if( answer == 24)
{
System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n" +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );
firstName = input.next();
lastName = input.next();
phoneNumber = input.nextLong();
System.out.printf(
"Thank you %s %s. We'll call you at %d if you're a winner.",
firstName,
lastName,
+ phoneNumber);
}
else if( answer != 24)
{
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!" );
}
}
}
}
else
{
do
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
--attempt;
System.out.printf("Enter the word of the day: ");
wordOfTheDay = input.nextLine();
} while (attempt >= 1);
if( attempt == 0)
{
System.out.print( "Sorry! You have no more attempts left!" );
}
}
}
I hope I made this clear enough.
To recap, I need to fix the problem with my do/while not letting me enter the correct word after a failed attempt.
Also, I need to get rid of the 3 * 8 = showing up after the users enters the correct input.
Normally, you would use the
breakstatement, but as you are not allowed settingattempt = -1will have the same effect:EDIT:
Move the
do { } while();to beforeifcheck: