java中的if else语句用于测试某些条件。它评估条件为trueor false。
true
false
if 语句分为三种类型。
if(condition) { // If condition is true, this block will be executed }
例如:
public class IfMain { public static void main(String[] args) { int price=20; if(price > 10) System.out.println("Price is greater than 10"); } }
输出:
输出: 价格大于 10 您可以在 if 之后编写单行后跟半色,或者您可以使用花括号编写代码块。
您可以在 if 之后编写单行后跟半色,或者您可以使用花括号编写代码块。
您可以重写上面的代码,如下所示。
public class IfMain { public static void main(String[] args) { int price=20; if(price > 10) { System.out.println("Price is greater than 10"); } } }
if(condition) { // If condition is true, this block will be executed } else { // If condition is false, this block will be executed }
例如: 检查数字是奇数还是偶数。
package org.arpit.java2blog; public class IfElseMain { public static void main(String[] args) { IfElseMain ieMain=new IfElseMain(); ieMain.checkOddOrEven(20); } public void checkOddOrEven(int number) { if(number%2==0) { System.out.println(number+" is even"); } else { System.out.println(number+" is odd"); } } }
20 is even
在我们了解 If else if 梯形语句之前,让我们先看看一些条件运算符。
Java 提供了许多条件运算符。其中一些是:
if(condition1) { // If condition1 is true, this block will be executed. } else if(condition2) { // If condition2 is true, this block will be executed. } else if(condition3) { // If condition3 is true, this block will be executed. } else { // If all above conditions are false, this block will be executed. }
package org.arpit.java2blog; public class IfElseIfLadderMain { public static void main(String[] args) { int age=28; if(age >= 18 && age <= 25) { System.out.println("Age is between 18 and 25"); } else if(age >= 26 && age <= 35) { System.out.println("Age is between 26 and 35"); } else if(age >= 36 && age <= 60){ System.out.println("Age is between 35 and 60"); } else{ System.out.println("Age is greater than 60"); } } }
Age is between 26 and 35
这就是java中的if else语句。
原文链接:https://codingdict.com/