如果性别=男性或女性打印结果

时间:2018-01-24 06:23:18

标签: java if-statement

git+https://github.com/begrossi/MediaScannerPlugin.git

无论用户输入什么,结果总是转到else语句。有什么方法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

在Java中,比较字符串的正确方法是使用'.equals'运算符。

更改所有

gender == "some string" 

gender.equals("some string") 

它应该可以正常工作。

答案 1 :(得分:1)

import java.util.Scanner;

public class test
{
public static void main(String[] args){
String gender;
Scanner scan = new Scanner(System.in);

System.out.println("What is your gender, male of female?");
    gender = scan.nextLine();


if( gender == "f"||gender =="F"||gender =="female"||gender=="Female"||gender =="FEMALE"){
    System.out.println("A female" );
}else if( gender == "m"||gender =="M"||gender =="male"||gender =="Male"||gender =="MALE")
{
    System.out.println("A male.");
}else{
    System.out.println("Unknown");
}
}
}

答案 2 :(得分:1)

试试这段代码

import java.util.Scanner;

public class test
{
 @SuppressWarnings("resource")
 public static void main(String[] args)
 {
    String gender;
    Scanner scan = new Scanner(System.in);

    System.out.println("What is your gender, male or female?");
    gender = scan.nextLine();


    if( gender.equals("f")||gender.equals("F")||gender.equals 
       ("female")||gender.equals("Female")||gender.equals("FEMALE"))
    {
       System.out.println("A female" );
    }

    if( gender.equals("m")||gender.equals("M")||gender.equals         
        ("male")||gender.equals("Male")||gender.equals("MALE"))
    {
       System.out.println("A male.");
    }

 }
}