簡單if分支語句
if分支語句:
if(exp1){
command1;
}else{
command2;
}
注:if一個花括號結束{},else一個花括號結束{}佑力;最后的else都可以省去包括嵌套的if分支語句
舉例:
/**
輸入一個數(shù)字,判斷其轉換為ASCII碼后的字母大小寫
*/
package test_java;
import java.util.Scanner;
public class Test13{
public static void main(String[] args){
System.out.println("請輸入一個數(shù): ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if(num>=65 && num <=90){
System.out.println("輸入的是大寫字母: "+(char)num);
}else{
System.out.println("輸入的是小寫字母: "+(char)num);
}
//輸入一個年份判斷式閏年還是平年(能被4整除远搪,但不能被100整除能被400整除)
int year = input.nextInt();
if(year%4==0 && year%100!=0 || year%400==0){
System.out.println("是閏年");
}else{
System.out.println("是平年");
}
}
}
if分支嵌套語句
if分支嵌套語句:嵌套的就是else if(exp2)這個語句
if(exp1){
command1;
}else if(exp2){
command2;
}else if(exp3){
command3;
}else{
command4;
}
舉例:
//給出一個百分制成績,要求輸出成績等級A/B/C/D/E,90分以上輸出A,80~89輸出B瓶竭,70~79輸出C,60~69輸出D渠羞,60以下輸出E
package test_java;
import java.util.Scanner;
public class Test14{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("請輸入一個成績:");
int score = input.nextInt();
if(score>=90){
System.out.println("成績?yōu)椋篈");
}else if(score<=89 && score>=80){
System.out.println("成績?yōu)椋築");
}else if(score<=79 && score>=70){
System.out.println("成績?yōu)椋篊");
}else if(score<=69 && score>=60){
System.out.println("成績?yōu)椋篋");
}else{
System.out.println("成績?yōu)椋篍");
}
}
}
if分支嵌套語句2——多層嵌套
if分支多層嵌套
if(exp1){
command1;
if(exp2){
command3;
}else{
command4;
}
}else{
command2;
if(exp3){
command5;
}else{
command6;
}
}
舉例:
/**
* if分支嵌套語句2——多層嵌套
*/
package test_java;
import java.util.Scanner;
public class Test15{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("今天的天氣如何:1—晴天 2-陰天");
int nu = input.nextInt();
if(nu==1){
System.out.println("天氣很好斤贰,是逛街還是逛公園:1-逛街 2-逛公園");
int nu1 = input.nextInt();
if(nu1==1){
System.out.println("逛街");
}else if(nu1==2){
System.out.println("逛公園");
}
}else if(nu==2){
System.out.println("天氣不好,是在家看電影還是打游戲:1-看電影 2-打游戲");
int nu1 = input.nextInt();
if(nu1==1){
System.out.println("看電影");
}else if(nu1==2){
System.out.println("打游戲");
}
}
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者