if语句:
格式:
if(关系表达式){
语句体;
}
案例:
public class ConstantDemo{
public static void main(String[] args) {
//定义两个变量
int a=1;
int b=2;
int max;
//使用if语句进行判断,如果a>b,则最大值为a,若a<b,则最大值为b
if (a>b) {
max =a;
System.out.println(a);
}
System.out.println(b);
System.out.println("结束");
}
}
执行流程:
1.首先计算关系表达式的值
2.如果关系表达式的值为true就执行语句体
3.如果关系表达式的值为false就不执行
4.继续执行后面的语句内容
if…else语句:
格式:if(关系表达式){
语句体1;
}else{
语句体2;
}
执行流程
1.首先计算关系表达式的值
2.如果关系表达式的值为true就执行语句体1
3.如果关系表达式的值为false就执行语句体2
4.继续执行后面的语句内容
案例:
import java.util.scanner; //导入控制台的数据
public class ConstantDemo{
public static void main(String[] args) {
//给出一个整数
scanner sc=new scanner(System.in);
System.out.println("请输入一个整数");
int Number =sc.nextInt();
//判断整数是偶数还是要分两种情况进行判断
if(Number%2 == 0){
System.out.println(Number);
}else
{
System.out.println(Number);
}
}
if…else语句:
格式:if(关系表达式){
语句体1;
}else{
语句体2;
}
…
else{
语句体n+1;
}
执行流程
1.首先计算关系表达式的值
2.如果关系表达式的值为true就执行语句体1
3.如果关系表达式的值为false就执行语句体2
4.继续执行后面的语句内容
案例:判断输入的一个礼拜的天数是星期几
import java.util.scanner;
public class ConstantDemo{
public static void main(String[] args) {
//给出一个整数
scanner sc=new scanner(System.in);
System.out.println("请输入一个天数");
int Number =sc.nextInt();
if (Number==1) {
system.out.println("今天是星期一");
else if(Number==2){
system.out.println("今天是星期二");
}
else if(Number==3){
system.out.println("今天是星期三");
}
else if(Number==4){
system.out.println("今天是星期四");
}
else if(Number==5){
system.out.println("今天是星期五");
}
else if(Number==6){
system.out.println("今天是星期六");
}
else if(Number==7){
system.out.println("今天是星期天");
}
}
system.out.println("结束!");
}
}
用if else语句判定考试成绩或的奖励
案列:
import java.util.scanner;
public class ConstantDemo{
public static void main(String[] args) {
System.out.println("请输入您的考试成绩");
scanner sc=new scanner(System.in);
int score =sc.nextInt();
//判定考试成绩获得的奖励
if (score <=100 ||score<0) {
System.out.println("您的输入出现了问题");
if (score>=95 &&score<=100) {
System.out.println("奖金100块");
}else if(score>=90 &&score<=94){
System.out.println("奖金90块");
}else if(score>=80 &&score<=89){
System.out.println("奖金70块");
}else if(score>=70 &&score<=79){
System.out.println("奖金60块");
}else if(score>=60 &&score<=69){
System.out.println("奖金50块");
}else if (score<=59) {
System.out.println("罚款100块");
}
}
System.out.println("执行结束");
}
}