首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在if-else语句中使用用户输入,以及如果用户输入不是所要求的,我如何循环返回代码?

如何在if-else语句中使用用户输入,以及如果用户输入不是所要求的,我如何循环返回代码?
EN

Stack Overflow用户
提问于 2018-12-01 01:33:29
回答 2查看 2.8K关注 0票数 -4

(此问题中的任何文本都来自于选择我的问题的答案之后)

这是针对我的问题给出的代码。我想让代码在用户输入"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?");
   }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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; 
    }
}
票数 1
EN

Stack Overflow用户

发布于 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;

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53562284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档