CapnCoin CapnCoin - 4 months ago 8
Java Question

i want my statement to re-execute if the condition if met false

So what i want to happen is that when the input is not "start" the if statement should run again asking for the user to input "start".
any ideas would be helpfull. thanks :)
example:

import java.util.Scanner;

import java.util.Random;

public class Words {

public static void main(String[]args){

Scanner scan = new Scanner(System.in);
String words[] = {"Iterate","Petrichor"};

System.out.println("type *start* to begin");
String input = scan.nextLine();

if (input.equals("start")){
String random = (words[new Random().nextInt(words.length)]);
System.out.println(random);
}
}

}

Answer

You would like to wrap your input reading in a loop:

import java.util.Scanner;

import java.util.Random;
public class Words {
  public static void main(String[]args){
    Scanner scan = new Scanner(System.in);
    String words[] = {"Iterate","Petrichor"};
    String input = "";

    while ( !input.equals("start") ) {
       System.out.println("type *start* to begin");
       input = scan.nextLine();
    }

    String random = (words[new Random().nextInt(words.length)]);
  }
}

Note that in your particular example the loop conditional works for your if statement so there was no need for the if statement.

Update

If you need to keep this running while the user types next you can wrap everything inside a do .. while loop so it executes at least once:

import java.util.Scanner;

import java.util.Random;
public class Words {
   public static void main(String[]args){
      Scanner scan = new Scanner(System.in);
      String words[] = {"Iterate","Petrichor"};
      String input = "";
      do {
         while ( !input.equals("start") ) {
            System.out.println("type *start* to begin");
            input = scan.nextLine();
         }

         String random = (words[new Random().nextInt(words.length)]);
         System.out.println("type *next* to repeat");
         input = scan.nextLine();
      }
   } while ( input.equals("next") );
}