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

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

Simple question about using names in else-if statements:

问题

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

  1. public class Else_If_Statements {
  2. public static void main(String[] args){
  3. int flavor = Chocolate;
  4. if (flavor == Vanilla)
  5. System.out.println("That will be 3$!");
  6. else if (flavor == Caramel)
  7. System.out.println("That will be 6$!");
  8. else if (flavor == Chocolate)
  9. System.out.println("That will be 5$!");
  10. else
  11. System.out.println("Sorry, that flavor isn't available!");
  12. }
  13. }
英文:

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 -->

  1. public class Else_If_Statements {
  2. public static void main(String[] args){
  3. int flavor = Chocolate;
  4. if (flavor = Vanilla)
  5. system.out.println(&quot;That will be 3$!&quot;);
  6. else if (flavor = Caramel)
  7. system.out.println(&quot;That will be 6$!&quot;);
  8. else if (flavor = Chocolate)
  9. system.out.println(&quot;That will be 5$!&quot;);
  10. else
  11. system.out.println(&quot;Sorry, that flavor isn&#39;t available!&quot;);
  12. }
  13. }

<!-- end snippet -->

答案1

得分: 2

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

  1. public class Else_If_Statements {
  2. public static void main(String[] args){
  3. String flavor = "Chocolate";
  4. if (flavor.equals("Vanilla"))
  5. System.out.println("That will be 3$!");
  6. else if (flavor.equals("Caramel"))
  7. System.out.println("That will be 6$!");
  8. else if (flavor.equals("Chocolate"))
  9. System.out.println("That will be 5$!");
  10. else
  11. System.out.println("Sorry, that flavor isn't available!");
  12. }
  13. }
英文:

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.

  1. public class Else_If_Statements {
  2. public static void main(String[] args){
  3. String flavor = &quot;Chocolate&quot;;
  4. if (flavor.equals(&quot;Vanilla&quot;))
  5. System.out.println(&quot;That will be 3$!&quot;);
  6. else if (flavor.equals(&quot;Caramel&quot;))
  7. System.out.println(&quot;That will be 6$!&quot;);
  8. else if (flavor.equals(&quot;Chocolate&quot;))
  9. System.out.println(&quot;That will be 5$!&quot;);
  10. else
  11. System.out.println(&quot;Sorry, that flavor isn&#39;t available!&quot;);
  12. }
  13. }

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:

确定