0
how would you code a user input scanner to respond with a set line?
This will probably sound confusing because I'm not entirely sure how to phrase this question, but how would you code a user input scanner to have a set response when someone inputs something, instead of just spitting the line they typed in back out again?
3 Antworten
+ 4
The program doesn't actually spit it back out unless you tell it to in the System.out.println method. When you're taking in user input, assign it to a variable. So Scanner input = new Scanner(System.in);
then, String wordEntered = input.nextLine();
this way, you now have their input stored in a variable that you can use throughout your program. To test conditions, you can use either an if statement or switch. When comparing strings, never use ==, always use .equals().
Example:
if(wordEntered.equals("Pickles")){
System.out.println("Strange thing to input, but whatever");
Other method
switch(wordEntered){
case "hello":
System.out.println("something something");
break;
case "Rawr":
System.out.println("what are you, a dinosaur?");
break;
With switch you just use the variable, the switch automatically uses .equals with Strings.
+ 2
i would use playerAnswer.equalsIgnoreCase(" "){
}
just so they can put the word in any case, but what ever is easy for you. :)
0
Could do that, I could also do (wordEntered.toLowerCase()) or Upper in the switch as well. But that's extra stuff that I didn't feel like writing a paragraph about