英文:
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("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!");
}
}
<!-- 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 = "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!");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论