Files
javaSE251223/day03/src/com/inmind/Demo01_if.java

151 lines
4.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;
/*
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_if {
//if的格式三的练习
public static void main(String[] args) {
int score =77;
if(score<0 || score>100){
System.out.println("你的成绩是错误的");
}else if(score>=90 && score<=100){
System.out.println("你的成绩属于优秀");
}else if(score>=80 && score<90){
System.out.println("你的成绩属于好");
}else if(score>=70 && score<80){
System.out.println("你的成绩属于良");
}else if(score>=60 && score<70){
System.out.println("你的成绩属于及格");
}else {
System.out.println("你的成绩属于不及格");
}
}
//if的格式三
public static void ifMethod3(String[] args) {
// x和y的关系满足如下
// x>=3 y = 2x + 1;
//-1<=x<3 y = 2x;
// x<-1 y = 2x 1;
// 根据给定的x的值计算出y的值并输出。
int x = -2;
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);
}
//if格式二的练习
public static void ifDemo2() {
//判断给定的整数是奇数还是偶数if-else
int i = 20;
//分析:奇数:%2余数为1反之为偶数
if (i % 2 == 1) {
System.out.println("变量i的值" + i + "为奇数");
//ctrl+D:复制一行
} else {
System.out.println("变量i的值" + i + "为偶数");
//ctrl+shift+上下,代码上下移动
}
System.out.println("程序结束");
}
//if的格式二
public static void ifMethod2() {
//判断2个值谁大
int a = 30;
int b = 20;
if (a > b) {
System.out.println("a的值大" + a);
} else {
System.out.println("b的值大"+b);
}
System.out.println("程序结束");
//使用三元运算符来实现
String str = a>b?"a大":"b大";
System.out.println(str);
}
//if的格式一
public static void ifMethod1(String[] args) {
//判断下变量对应的值
int i = 12;
if (i!=10){
System.out.println("i不为10");
}
System.out.println("程序结束");
//判断2个值谁大请用if判断流程来判断
int a = 10;
int b = 20;
//ctrl+shift+enter
if (a > b) {
System.out.println("a的值大"+a);
}
if (b > a) {
System.out.println("b的值大"+b);
}
}
}