如何根据字符串值打印结果?

huangapple go评论66阅读模式
英文:

How to print a result depends on String value?

问题

我对Java非常陌生,想请您帮助我。
我有这段代码:

public class Person {

    String name;
    String gender;

    public static void main(String[] args) {
        Person person = new Person();
        person.name("Max");
        person.gender = "male";
        
        Person person2 = new Person();
        person2.name = "Lea";
        person2.gender = "female";
    }

以下是对下面方法的正确语法是什么?我应该将String转换为boolean吗?

if (String = male) {
    System.out.println("You are man!");
} else {
    System.out.println("You are woman!");
}

谢谢
英文:

I am very new to Java and would ask you for help.
I have this:

public class Person {

String name;
String gender;

public static void main(String[] args) {
    Person person = new Person();
	person.name("Max");
	person.gender = "male";
	
	Person person2 = new Person();
	person2.name = "Lea";
	person2.gender = "female";
}

What should be the correct syntax for the following method? Should I convert String to boolean?

if (String = male) {
    System.out.println("You are man!")
} else{
    System.out.println("You are woman!")

Thank you!

答案1

得分: 0

以下是翻译好的内容:

正确的方式应该是:

if (person.gender.equals("male")) {
    System.out.println("You are man!");
} else {
    System.out.println("You are woman!");
}

在这里,您可以用您想要进行比较的变量来替换字符串。

英文:

The correct way would be

if (person.gender.equals("male")) {
    System.out.println("You are man!")
} else{
    System.out.println("You are woman!")
}

Where you can replace the String with the variable you would like to compare.

答案2

得分: 0

if (String = male) 不是有效的语法,甚至无法编译通过。您需要访问该字段,将其与字符串进行比较(male 不是字符串,"male" 才是),= 是赋值操作,但您想要进行相等性比较... 如果您尝试使用 == 来比较字符串,请不要这样做。字符串的比较应该使用 equals() 方法来进行。如果您要将变量与常量字符串值进行比较,请在常量字符串值上调用 equals 方法,因为该变量可能为空,您不希望触发 NullPointerException。所以,总结一下:假设 gender 字段是可访问的,应该这样写:if ("male".equals(myPerson.gender))

英文:

if (String = male) is not valid syntax and won't even compile. You need to access the field, you need to compare it to a string (male is not a string, "male" is), = assigns a value but you want to compare for equality... If you are ever tempted to compare strings with == don't. String comparisons are done with the equals() method. And if you are going to compare a variable with a constant string value, call equals on the constant string value, because the variable can be null and you don't want to trigger a NullPointerException. So, to sum up: if ("male".equals(myPerson.gender)), assuming the gender field is accessible.

huangapple
  • 本文由 发表于 2020年9月1日 21:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63689090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定