如果/ Else结果基于用户输入

时间:2014-11-04 23:40:27

标签: java input java.util.scanner

所以我是java新手,有点困惑。通过学习我刚学过的知识并用它创建自己的小程序,我学得最好,只是为了帮助理解工作原理。

我遇到了一个学习如何使用用户输入并将其等同于某事的问题。基本上我希望用户输入他们的性别,并根据他们的答案,使用if / else获得响应。这是我现在关于该区域的所有代码,我真的很困惑如何从输入中获取答案,然后使用if / else检查它。

Scanner four = new Scanner(System.in);
System.out.println("So, what gender did you say you were?");

//Add if/else statement response here that will be called based on user input

3 个答案:

答案 0 :(得分:2)

首先,获取用户的回复......

Scanner four = new Scanner(System.in);
System.out.println("So, what gender did you say you were?");

// What the user said...
String response = four.nextLine();

然后,使用String.equalsString.equalsIgnoreCase来测试结果......

if ("M".equalsIgnoreCase(response) || "MALE".equalsIgnoreCase(response)) {
    // If the user responded with "m" or "male"...
} else if ... {// set up female response
} else {
    // Default response...
}

如果遇到困难,请考虑查看官方教程,例如The if-then and if-then-else Statements

答案 1 :(得分:0)

试试这个:

Scanner input = new Scanner(System.in);
System.out.println("So, what gender did you say you were?");
String four=input.nextLine();

if(four.equals("xyz"){
 //Do something
}
else{
  //Do Something else
}

答案 2 :(得分:0)

谢谢大家快速回复!这是我遗失的一段代码..

String four=input.nextLine();
相关问题