import java.util.Scanner;
public class SecretWord {
public static void main( String[] args ) {
Scanner input = new Scanner(System.in);
String secret = "Please", guess;
System.out.print( "Secret word?" );
guess = input.next();
for (int i = 0; guess.equals(secret); i++) {
if( guess.equals(secret) ) {
System.out.println("enter");
} else {
System.out.println( "try again" );
}
}
}
}
How do I make it so that, when a user enters anything other than "Please", it will ask him/her to try again? Then the user will have to enter "Please", end the loop, and print "Enter".
You have to move the
input.next()
inside of the loop and I would recommand to use awhile
instead of afor
loop:Use a while loop instead,
Apart from this, the for loop have the following syntax,
This means that for you the loop will be like this,
Since this condition will never hold for the first loop you will never enter the for loop at all.
You can also use do-while which uses a post test,
This is one of the classic examples where the use of 'do-while' construct is encouraged(and there are a very few). But it seems that you explicitly want to use 'for', therefore following is the code using 'for':
I hope this works. Now comes the implementation using 'do-while' :
Try This: