Java程序扫描程序和字符串 [英] Java program scanner and string

查看:82
本文介绍了Java程序扫描程序和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!谁能告诉我这个java程序有什么问题?它总是执行第二个条件(否则)并且不识别第一个条件?

非常感谢。



我有什么试过:



Hi! Can anyone tell me what is wrong with this java program?? it always executes the second condition (else) and doesn t recognize the first?
Thanks a lot.

What I have tried:

import java.util.Scanner; 
public class Main 
{ 
public static void main(String[] args) 
{ 
System.out.println("Choose your gender:"); 
Scanner sc=new Scanner(System.in); 
String gender=sc.nextLine(); 
if(gender=="female") 
{System.out.println("Hi"); 
} 
else{ 
System.out.println("sorry"); 
} 

} 
}

推荐答案

不要使用 == 这里:使用 gender.equals(female)而不是 gender ==female



在此处阅读原因: Java String.equals与== - Stack Overflow [ ^ ]或此处:我如何比较Java中的字符串? - 堆栈溢出 [ ^ ]
Don't use == here: use gender.equals("female") rather than gender == "female"

Read the reason here: Java String.equals versus == - Stack Overflow[^] or here: How do I compare strings in Java? - Stack Overflow[^]


只是一个疯狂的猜测,但我会说性别==女性条件永远不会解析为 true



您可能想了解的内容性别是指您希望条件为 true
Just a wild ass guess, but I'd say that gender == "female" condition never resolves to true.

You might want to find out what the contents of gender is when you expect the condition to be true.


建议:通常的做法是帮助检查用户输入。

这种做法是将用户输入转换为小写或大写。这样,女性,女性或女性等输入都将与测试相匹配。
Advice: There is a common practice to help check user inputs.
That practice is to convert user inputs to lowercase or uppercase. This way, inputs like 'female', 'Female' or 'FEMALE' will all match the test.


这篇关于Java程序扫描程序和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆