Reputation: 53
What I would like to happen here is to have the user input "start". if the user inputs start the program must give a random word from the array and then ask for the user to input "next", when the user inputs "next" the program gives another random word, then the program asks for "next" to be input again and so forth... you get the idea.
here is some code, I thought would produce this effect but all it does is prints "Type start to see a cool word" user input "start" and then the program returns nothing.
Any advice would be appreciated and if you could tell me why my code is doing this I would be really appreciative because that way I can learn from this. Thanks
here is the code i wrote:
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 = "";
System.out.println("type *start* to see a cool word");
input = scan.nextLine();
while(!input.equals("start")){
String random = words[new Random().nextInt(words.length)];
System.out.println(random);
System.out.println();
System.out.println("type *next* to see another cool word");
while(input.equals("next"));
}
}
}
Upvotes: 1
Views: 372
Reputation: 654
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 {
do {
System.out.println("type *start* to begin");
input = scan.nextLine();
} while ( !input.equals("start") );
String random = (words[new Random().nextInt(words.length)]);
System.out.println("type *next* to repeat");
input = scan.nextLine();
}
} while ( input.equals("next") );
}
Upvotes: 1