Java If语句帮助初学者

时间:2013-01-18 21:43:53

标签: java if-statement

我只是在学习java,所以这可能是一个非常愚蠢的问题,但我找不到一个简单的答案。我正在尝试制作程序,如果用户输入“male”来运行System.out.print(“你是一个人”);
这是我的代码:

    import java.util.Scanner;

public class clac {
    public static void main(String[] args){
        double gender;
        Scanner input = new Scanner(System.in);
        System.out.print("Are you male or female? ");
        gender = input.nextDouble();
        if (gender == "male"){
            System.out.println("You are a guy");
        }else{
            System.out.print("You are a gal.");
        }
    }
}

5 个答案:

答案 0 :(得分:5)

你做错了什么:你需要读一个字符串。 String是一段文本。双精度是十进制数。你正在阅读双人。

如何解决:

String gender = input.next(); // read a String, instead of double
if (gender.equals("male")) // if (gender == "male") use .equals for strings
{
    System.out.println("U mad bro!?");
} else
{
    System.out.println("Hey Doll!");
}

答案 1 :(得分:0)

您不应该使用引用小数的nextDouble()

答案 2 :(得分:0)

尝试

  String gender = input.nextString();
    if ("male".equals(gender)){
        System.out.println("Wazzup dude?");
    }else{
        System.out.print("Hey Doll!");
    }

答案 3 :(得分:0)

我相信您希望将 .next()方法用于扫描仪。尝试这样的事情:

import java.util.Scanner;

public class clac {
    public static void main(String[] args){
        //Define gender variable as a string since that's what we're expecting as an input
        string gender;
        //Instantiate a Scanner object
        Scanner input = new Scanner(System.in);
        //Ask the user a question
        System.out.print("Are you male or female? ");
        //Read in the response into the gender variable
        gender = input.next();
        //Check to see if the user's answer matches "male"
        //We put "male" first in case the user returns a null value
        //This will help avoid a fatal error
        if ("male".equals(gender)){
            System.out.println("You are a guy");
        }
        else {
            System.out.print("You are a gal.");
        }
    }
}

我希望这会有所帮助。

答案 4 :(得分:0)

你应该用equals方法比较两个字符串,字符串是一个对象,这是一个引用,equals()方法会比较两个字符串的内容,但是==会比较两个字符串的地址

所以,你应该这样写:

gender = input.next();
if (gender.equals("male")){
    System.out.println("You are a guy");
}else{
    System.out.print("You are a gal.");
}