-4

(现在这个问题中的任何文字都是在选择我的问题的答案之后)

这是为我的问题提供的代码。我希望代码在用户输入“是”或“否”时执行某些任务,因此我需要知道如何将用户输入实现到 if-else 语句中。我还想了解如何将代码循环回输入“是”或“否”以外的任何内容的用户输入。

    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?");
   }
}
4

2 回答 2

1

首先你想用你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-11-30T18:03:26.527 回答
0

如果您希望用户只输入“是”/“否”并要求他们再次输入直到他们正确输入,您可以使用 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;

    }
于 2018-11-30T18:52:39.037 回答