2014-11-04 24 views
-3

所以我对java很陌生并且有点困惑。我通过学习刚刚接受的教学并创建自己的小程序来学习,帮助理解工作原理。If/Else result based off of user input

我遇到了一个问题,学习如何使用用户输入并将其与某事等同起来。基本上我想要一个用户输入他们的性别,并根据他们的答案,使用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 
+0

你有没有试过?我们可以看到它吗? – Pshemo 2014-11-04 23:44:01

回答

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

+0

谢谢!这是一个详细的答案。我缺乏部分字符串响应= four.nextLine();我想这是程序检查和识别用户说什么?基本上是结果?然后我们在if/else中引用结果。 – austinj1022 2014-11-04 23:58:13

+0

'nextLine'正在读取用户的回复(等待直到按下回车键),'if/else if/else'是您以任何方式处理该回复。 – MadProgrammer 2014-11-05 00:01:19

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 
} 
+1

谢谢!这工作!我错过了关于String four = input.nextLine()的部分; – austinj1022 2014-11-04 23:56:13

0

感谢球员们的快速反应!这是我丢失的那段代码..

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