(此问题中的任何文本都来自于选择我的问题的答案之后)
这是针对我的问题给出的代码。我想让代码在用户输入"Yes“或"No”时执行某些任务,因此我需要知道如何将用户输入实现到if-else语句中。我还想知道如何将代码循环回用户输入,而不是输入"Yes“或"No”。
import java.util.Scanner;
public class RandomPerkSelector {
public static void main(String [] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Are you playing as a survivor?");
}
}
发布于 2018-12-01 02:03:27
首先,您希望使用Scanner
从键盘读取数据。你已经走到一半了:
Scanner userInputReader = new Scanner(System.in);
String userInput = userInputReader.nextLine();
您可以简单地检查userInput
是否等于yes
/no
,如下所示:
if(userInput.equals("yes")){ //note strings are compared with .equals, not ==
//"yes" case
}else if(userInput.equals("no")){
//"no" case
}else{
//neither "yes" nor "no"
}
或者,switch语句也可以工作
switch(userInput){
case "yes":
//yes case
break;
case "no":
//no case
break;
default:
//neither "yes" nor "no"
break;
}
如果给定了无效的输入,则使其请求更多的输入:
while(true){
String userInput = userInputReader.nextLine();
if(userInput.equals("yes")){ //note strings are compared with .equals, not ==
//"yes" case
//generate your numbers for "yes"
break;
}else if(userInput.equals("no")){
//"no" case
//generate your numbers for "no"
break;
}else{
//neither "yes" nor "no"
//note that the continue statement is redundant and
//the whole else-block can be omitted
continue;
}
}
发布于 2018-12-01 02:52:39
如果您希望用户只输入"yes"/"no“,并要求他们再次输入,直到正确为止,您可以使用do while循环。在此之后,您可以使用Switch语句来控制程序流。像这样
Scanner sc = new Scanner(System.in);
String userInput;
do{
System.out.println("Input : ");
userInput = sc.nextLine();
}while("yes".equalsIgnoreCase(userInput)==false && "no".equalsIgnoreCase(userInput)==false);
switch(userInput){
case "yes":
//do something
break;
case "no":
//do something
break;
default:
//do something
break;
}
https://stackoverflow.com/questions/53562284
复制相似问题