Files
javaSE260715-new/day03/src/com/inmind/if01/Demo01.java
T

119 lines
3.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.inmind.if01;
/*
if格式一:
if(判断条件){
语句;
}
执行顺序:先执行判断条件,判断条件必须是布尔型的结果,
如果为true,就执行大括号内部的语句,false就直接跳过大括号中的内容
---------------------------------------------------------------
if格式二:
if(判断条件){
语句1
}else{
语句2
}
执行顺序:先执行判断条件,判断条件必须是布尔型的结果,
如果为true,就执行大括号语句1,这时else就不执行,
如果为false就直接跳过if后面大括号中的语句1直接执行else后面的语句2
注意:格式二,语句1或语句2肯定会执行一个,但是也永远都只会执行一个
在某种简单的逻辑之下,三元运算符可以跟if-else互换,但是在开发中if-else的使用场景更广
------------------------------------------------------------------
if格式三:
if(判断条件1){
语句1
}else if(判断条件2){
语句2
}else if(判断条件3){
语句3
}....
else{
语句n;
}
执行顺序:先执行判断条件1,判断条件必须是布尔型的结果,
如果为true,就执行大括号语句1,这时结束了整个if语句,
如果为false就直接跳过if后面大括号中的语句1继续向下判断判断条件2
如果为true,就执行大括号语句2,这时结束了整个if语句
如果为false就直接跳过if后面大括号中的语句2继续向下判断....
最终如果所有的判断条件都为false,那么就直接执行else后面的语句n
注意:格式三,肯定会执行一个语句,但是也永远都只会执行一个语句;
*/
public class Demo01 {
/*
案例:
x和y的关系满足如下:
x>=3 y = 2x + 1;
-1<=x<3 y = 2x;
x<=-1 y = 2x 1;
根据给定的x的值,计算出y的值并输出
*/
public static void main(String[] args) {
//定义一个整数变量
int x = -4;
int y ;//先定义后赋值
if (x >= 3) {
y = 2*x+1;
} else if (x >= -1 && x < 3) {
y = 2*x;
} else{
y = 2*x-1;
}
System.out.println("y的值为"+y);
}
//if-格式二
public static void ifMethod2(String[] args) {
//判断2个值谁大
int a = 10;
int b = 20;
if (a < b) {
System.out.println("b的值大,值为:" + b);
} else {
System.out.println("a的值大,值为:" + a);
}
System.out.println("程序结束");
System.out.println("-----------------");
//使用三元运算符判断2个值谁大
String str = a > b ? "a的值大,值为:" + a : "b的值大,值为:" + b;
System.out.println(str);
}
//if-格式一
public static void ifMethod() {
//定义整数变量
int i = 10;
if (i != 10) {
System.out.println("i等于10");
}
System.out.println("程序结束");
System.out.println("-----------------");
//判断2个值谁大
int a = 10;
int b = 20;
if (a > b) {
System.out.println("a的值大,值为:"+a);
}
if (a < b) {
System.out.println("b的值大,值为:"+b);
}
}
}