if else条件语句
Posted bomily0212
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了if else条件语句相关的知识,希望对你有一定的参考价值。
Java 条件语句
- if
- if…else
- if…else if…else
- if…else嵌套
if
语法格式:
if(表达式){ //如果表达式结果位true 那么执行这里的代码 }
示例
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("这是 if 语句");
}
}
}
if…else
语法格式:
if(布尔表达式){ //true }else{ //false }
示例
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("这是 if 语句");
}else{
System.out.print("这是 else 语句");
}
}
}
if…else if…else
语法格式:
if(布尔表达式 1){ //如果布尔表达式 1的值为true执行代码 }else if(布尔表达式 2){ //如果布尔表达式 2的值为true执行代码 }else if(布尔表达式 3){ //如果布尔表达式 3的值为true执行代码 }else { //如果以上布尔表达式都不为true执行代码 }
注意:
- 最多有一个else语句
- 可以有若干个else if语句,但必须再else之前
- 一旦其中一个else if语句检测为true,其他的else if以及else都会被跳过。
示例
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("这是 else 语句");
}
}
}
if…else嵌套
语法格式:
if(布尔表达式 1){ ////如果布尔表达式 1的值为true执行代码 if(布尔表达式 2){ ////如果布尔表达式 2的值为true执行代码 } }
示例
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
以上是关于if else条件语句的主要内容,如果未能解决你的问题,请参考以下文章