关于在 else-if 语句中使用名称的简单问题:

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

Simple question about using names in else-if statements:

问题

我是新手,需要一些关于如何在Java中使用变量的指导。我尝试使用变量来触发条件语句,但我不知道它们是如何工作的。

public class Else_If_Statements {
    public static void main(String[] args){

        int flavor = Chocolate;
        
        
        if (flavor == Vanilla)
            System.out.println("That will be 3$!");
        else if (flavor == Caramel)
            System.out.println("That will be 6$!");
        else if (flavor == Chocolate)
            System.out.println("That will be 5$!");
        else 
            System.out.println("Sorry, that flavor isn't available!");
    }
}
英文:

I'm new and I need some guidance on how to use names in Java. I tried to use names to trigger the else if statements but I don't know how they work.

<!-- language: lang-java -->

public class Else_If_Statements {
    public static void main(String[] args){

        int flavor = Chocolate;
        
        
        if (flavor = Vanilla)
            system.out.println(&quot;That will be 3$!&quot;);
        else if (flavor = Caramel)
            system.out.println(&quot;That will be 6$!&quot;);
        else if (flavor = Chocolate)
            system.out.println(&quot;That will be 5$!&quot;);
        else 
            system.out.println(&quot;Sorry, that flavor isn&#39;t available!&quot;);
    }
}

<!-- end snippet -->

答案1

得分: 2

在Java中,if else的工作方式如下。要分配给String数据类型的命名值,并且必须使用equals()方法进行比较。

public class Else_If_Statements {
    public static void main(String[] args){

        String flavor = "Chocolate";


        if (flavor.equals("Vanilla"))
            System.out.println("That will be 3$!");
        else if (flavor.equals("Caramel"))
            System.out.println("That will be 6$!");
        else if (flavor.equals("Chocolate"))
            System.out.println("That will be 5$!");
        else 
            System.out.println("Sorry, that flavor isn't available!");
    }
}
英文:

In Java, the if else works this way. The named value to be assigned to the String datatype and equals() method has to be used for the comparison.

public class Else_If_Statements {
    public static void main(String[] args){

        String flavor = &quot;Chocolate&quot;;
        
        
        if (flavor.equals(&quot;Vanilla&quot;))
            System.out.println(&quot;That will be 3$!&quot;);
        else if (flavor.equals(&quot;Caramel&quot;))
            System.out.println(&quot;That will be 6$!&quot;);
        else if (flavor.equals(&quot;Chocolate&quot;))
            System.out.println(&quot;That will be 5$!&quot;);
        else 
            System.out.println(&quot;Sorry, that flavor isn&#39;t available!&quot;);
    }
}

huangapple
  • 本文由 发表于 2020年10月12日 13:33:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64312199.html
匿名

发表评论

匿名网友

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

确定