Java学习-Java基础(4)

一、学习目标:

掌握Java中程序控制结构的相关知识,包括顺序、分支、循环控制结构,以及三个关键字。


二、学习内容:

1、顺序控制

程序从上到下的执行,中间没有任何判断和跳转

例如:Java中定义变量时采用合法的前向引用(先定义后引用)

2、选择结构(分支控制)(if-else,switch)

让程序有选择的执行

单分支

if(条件表达式){

执行代码块;

}

当表达式为true,执行 {} 中的语句,若为false则不执行

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter Your age: ");
      int age = sc.nextInt();
      if(age >= 18){
      System.out.println("You are old");
      }
   }
}

双分支

if(条件表达式){

代码块1;

}else{

代码块2;

}

当表达式成立时,执行代码块1,否则执行代码块2

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter Your age: ");
      int age = sc.nextInt();
      if(age >= 18){
      System.out.println("You are old");
      }else{
         System.out.println("You are young");
      }
   }
}

判断闰年

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   int year = sc.nextInt();
   if((year % 4 == 0 && year % 100 != 0)|| (year % 400 == 0)){
         System.out.println(year+"是闰年");
      }else{
         System.out.println(year+"不是闰年");
      }
   }
}

多分支  

if-else-if

基本语法:

if( 条件表达式1){

代码块1;

}else if(条件表达式2){

代码块2;

}……

else{

代码块n;

}

说明:

(1)多分支可以没有else

(2)多分支最多只能有一个执行入口;若无else且所有表达式均不成立,则没有执行入口

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   int year = sc.nextInt();
   //确保输入为int类型的年份,涉及后面的异常知识
   //应当加入限制条件进行合理性判断
   if(year>=2020){
   System.out.println("输入错误,输入2020年以前的年份");
   } else if(year >= 2010) {
   System.out.println("你是10后");
   }else if(year>=2000 && year<2010){
      System.out.println("你是00后");
   }else if(year>=1990 && year<2000){
      System.out.println("你是90后");
   }else{
      System.out.println("你好,老同志!");
      }
   }
}
import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
   System.out.println("输入成绩:");
      int grade = sc.nextInt();
   System.out.print("评级鉴定为:");
   //确保输入为int类型的年份,涉及后面的异常知识
   //应当加入限制条件进行合理性判断:使用双分支嵌套多分支的方式
   if (grade >= 0 && grade <= 100) {
      if(grade == 100){
         System.out.println("perfect");
      }else if(grade>=90 && grade < 100){
         System.out.println("excellent");
      }else if(grade>=80 && grade < 90){
         System.out.println("good");
      }else if(grade>=70 && grade < 80){
         System.out.println("average");
      }else if(grade>=60 && grade < 70){
         System.out.println("pass");
      }else if(grade < 60){
         System.out.println("not pass");
      }
   }else{
      System.out.println("Not a valid grade");
   }
   }
}
嵌套分支

在一个分支结构中又完整的嵌套了另一个完整的分支结构,里面的是内层分支,外面的是外层分支,规范:不要超过三层(可读性不好)

基本语法:

if(){

        if(){

       //if-else...

        }else if(){

        //if-else

        }

}

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
   System.out.println("输入成绩:");
      double grade = sc.nextDouble();
      char gender = sc.next().charAt(0);
   System.out.print("结果为:");
   if(grade > 8.0){
      System.out.println("进入决赛");
      if(gender == '男'){
         System.out.println("进入男子组");
      }else if(gender == '女'){
         System.out.println("进入女子组");
      }
   }else{
      System.out.println("被淘汰");
    }
  }
}
import java.util.Scanner;
//嵌套分支应用案例
public class Main {
   public static void main(String[] args) {
      int price = 60;
   Scanner sc = new Scanner(System.in);
   System.out.println("输入月份:");
   int month = sc.nextInt();
   System.out.println("输入年龄");
   int age = sc.nextInt();
   if (month <= 10 && month >= 4) {
      System.out.println("当前为旺季");
      if (age < 18) {
         System.out.println("票价为:"+(price>>1));
      }else if(age >= 18 && age <= 60){
         System.out.println("票价为:"+price);
      }else if(age > 60){
         System.out.println("票价为:"+price/3);
      }
   }else if((month <= 12 && month >= 10)||month >= 1 && month < 4){
      System.out.println("当前为淡季");
      if (age >= 18) {
         System.out.println("票价为:40");
      }else if(age >=0 && age < 18){
         System.out.println("票价为:20");
      }else{
         System.out.println("年龄不合法,重新输入");
      }
   }else{
      System.out.println("月份不合法");
   }
  }
}
switch分支结构

基本语法

switch(表达式){

case 常量1: 语句块1;//当……

break;

case 常量2: 语句块2;

break;

……

case 常量n: 语句块n;

break;

default:

default语句块;

break;

}

1、switch关键字,表示switch分支

2、表达式对应一个值

3、case 常量1:当表达式为常量1时,就执行语句块1

4、break表示退出switch

5、如果和case1匹配,就执行语句块1;否则继续去匹配case常量2

6、如果一个都没有匹配上,执行default

7、穿透现象:若匹配到case,执行该语句块后,无break语句,则会直接执行下一语句块。

switch流程图:

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
      System.out.print("输入a-g:");
      char ch = sc.next().charAt(0);
   switch(ch){
         //a => 97 A => 65
         case 'a':
            System.out.println("Monday");
            break;
         case 'b':
            System.out.println("Tuesday");
            break;
         case 'c':
            System.out.println("Wednesday");
            break;
         case 'd':
            System.out.println("Thursday");
            break;
         case 'e':
            System.out.println("Friday");
            break;
         case 'f':
            System.out.println("Saturday");
            break;
         case 'g':
            System.out.println("Sunday");
            break;
         default:
            System.out.println("不存在的日期");
            break;
     }
     System.out.println("switch执行结束,继续执行程序");
  }
}

switch细节注意:

  • 表达式数据类型,应和case后的常量类型一致,或者是可以自动转成可以想和比较多类型,比如输入的是字符,而常量是int('a' => 97 'A' => 65)
  • switch(表达式)中的表达式的返回值必须是:(byte,short,int,char,enum,String)
  • case子句中的值必须是常量,而不能是变量
  • default子句是可选的,当没有可匹配的case时,执行default
  • break语句是用来在执行完一个case语句后使程序跳出switch语句块,若没有break,程序会顺利执行到switch末尾,除非遇到break
import java.util.Scanner;
//switch判断成绩合格与否
public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.print("输入成绩:");
       int grade = sc.nextInt();
       if (grade >= 0 && grade <= 100) {
           switch (grade / 60) {
               //a => 97 A => 65
               case 0:
                   System.out.println("不合格");
                   break;
               case 1:
                   System.out.println("成绩合格");
                   break;
               default:
                   System.out.println("成绩不符");
                   break;
           }
           System.out.println("switch执行结束,继续执行程序");
       }else{
           System.out.println("成绩不合法");
       }
   }
}

switch语句和if-else比较:

1、如果判断的具体数值不多,而且符合byte,int,short,char,enum,String这六种类型,这时建议使用switch语句

2、其他情况:对区间进行判断时,对结果为boolean类型判断,使用if,if的使用范围更广

import java.util.Scanner;
//使用穿透
public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.print("输入月份:");
       int month = sc.nextInt();
       switch(month){
           case 3:
           case 4:
           case 5:
               System.out.println("春季");
               break;
           case 6:
           case 7:
           case 8:
                System.out.println("夏季");
                break;
           case 9:
           case 10:
           case 11:
               System.out.println("秋季");
               break;
           case 12:
           case 1:
           case 2:
               System.out.println("冬季");
               break;
       }
   }
}

3、循环控制(for,while,do while,多重循环)

for循环控制

基本语法

for(循环变量初始化;循环条件;循环变量迭代){

循环操作(可以多条语句);

}

  • for关键字,表示循环控制
  • for循环四要素:循环变量初始化、循环条件、循环操作、循环变量迭代
  • 循环操作可以有多条语句
  • 若循环操作只有一条语句,可以省略{},最好不省略

for循环的注意事项和细节说明:

循环条件是返回布尔值的表达式

for(;循环判断条件;)中的初始化和变量迭代可以写在其他地方,但是分号不能省略

循环初始值可以有多条初始化语句,但是要求类型一样,中间用逗号隔开,循环变量迭代也可以有多条变量迭代语句,中间用逗号隔开

public class Main {
   public static void main(String[] args) {
       int i = 1;
       for(;i <= 10;){
           System.out.println(i);//输出1到10
           i++;
       }
       System.out.println(i);//11
   }
}

for(;;)指无限循环

public class Main {
   public static void main(String[] args) {
       for(int i = 0,j = 0;i < 3; i++,j += 2){
           System.out.println("i = "+i+",j = "+j);
       }
   }
}
public class Main {
   public static void main(String[] args) {
       int count = 0;
       int sum = 0;
       for(int i = 0;i < 100; i++){
           if( i % 9 == 0){
               System.out.println(i);
               sum += i;
               count++;
           }
       }
       System.out.println(sum);
       System.out.println(count);
   }
}
public class Main {
   public static void main(String[] args) {
       for(int i = 0,j = 5;i <= 5;i++,--j){
               System.out.println(i+"+"+j+"="+(i+j));
       }
   }
}
while循环控制

基本语法

循环变量初始化;

while(循环条件){

循环体语句;

循环变量迭代;

}

  • while循环也有四要素,只是四要素放的位置不同
 int i = 0 ;//变量初始化
        //循环条件
       while( i <= 10 ){
           System.out.println(i);//循环体
           ++i;//循环变量迭代

while流程图:

while循环注意事项:

  • 循环条件返回布尔值
  • while循环先判断再执行

while循环示例:

public class Main {
   public static void main(String[] args) {
       int i = 1 ;
       System.out.println("1~100"+"的所有能被3整除的数:");
       while( i <= 100 ){
           if(i % 3 == 0 ) {
               System.out.println(i);
           }
           i++;
       }
       int j = 40;
       System.out.println("40~100"+"的所有偶数:");
       while( j <= 200 ){
           if(j % 2 == 0) {
               System.out.println(j);
           }
           j++;
       }
   }
}
do-while循环

基本语法:

do{

循环体语句;

循环变量迭代;

}while(循环条件);

说明:

  1. do-while是关键字
  2. 也有循环四要素
  3. 先执行,在判断,至少会执行一次
  4. 最后有个分号
  5. while和do-while区别:while先判断后执行,可能一次不执行;do-while先执行后判断,至少执行一次

public class Main {
   public static void main(String[] args) {
       int i = 1;
       do{
           System.out.println(i);
           i++;
       }while(i <= 10 );
   }
}
public class Main {
//统计1-200之间可以被5整除,不可被3整除的个数   
public static void main(String[] args) {
       int i = 1;
       int j = 1;
       int sum = 0;
       int count = 0;
       do{
           System.out.println(i);
           sum += i;
           i++;
       }while(i <= 100 );
       System.out.println(sum);
       do{
        if(j % 5 == 0 && j % 3 != 0) {
            System.out.println(j);
            count++;
        }
        j++;
        }while( j <= 200 );
        System.out.println(count);
   }
}
import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      char answer;
      do{
         System.out.println("Hello! answer me "+" Y/N ");
         answer = sc.next().charAt(0);
         System.out.println("Your answer is "+answer);
      }while(answer != 'Y');
   }
}
多重循环
  • 将一个循环体放在另一个循环体内,就形成了嵌套循环,其中,for,while,do-while均可作为内层、外层循环(一般为两层,最多三层,否则可读性差)
  • 实质上,嵌套循环就是把内层循环当作外层循环的循环体,当只有内层循环的循环条件为false时,才会完全跳出内层循环,才可结束外层的当次循环,开始下一次的循环
  • 若外层循环执行m次,内层循环执行n次,那么内层循环体实际执行m*n次
//统计三个班,每个班五名同学的成绩,求出各班平均分和所有班级平均分,以及每个班的及格人数
import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      double allSum = 0;
      for(int i = 1; i <= 3; i++){
         double grade;
         double sum = 0;
         int count = 0;
         System.out.print("输入成绩:");
         for(int j = 1; j <=5 ; j++){
            grade = sc.nextDouble();
            if(grade >= 60){
               count++;
            }
            sum += grade;
         }
         double average = sum/5.0;
         allSum += sum;
         System.out.println(i+"班的平均分为"+average);
         System.out.println(i+"班"+"及格人数为:"+count+"人");
      }
      System.out.println("所有班级的平均分:"+allSum/15);
      sc.close();
   }
}
//九九乘法表     
 for(int i = 1; i <= 9 ; i++){
         for(int j = 1 ; j <= i ; j++){
            System.out.print(j + "*"+i + "=" + i*j + "\t");
         }
         System.out.println();
      }
      for(int i = 1; i <= 5 ; i++){
         for(int j = 1 ; j <= i ; j++){
            System.out.print("*");
         }
         System.out.println();
      }

运行效果:

*
**
***
****
*****

for(int i = 1; i <= 5 ; i++){//i表示层数
         for(int j = 1 ; j <= 2*i - 1 ; j++){
            System.out.print("*");
         }
         System.out.println();
      }

运行效果:

*
***
*****
*******
*********

      for(int i = 1; i <= 5 ; i++){
         for(int k = 1; k <= 5-i ; k++){
            System.out.print(" ");
         }
         for(int j = 1 ; j <= 2*i-1 ; j++){
            System.out.print("*");
         }
         System.out.println();
      }

运行结果:

    *
   ***
  *****
 *******
*********

//打印空心金字塔
      int totalLevel = 100;
      for(int i = 1; i <= totalLevel ; i++){
         for(int k = 1; k <= totalLevel-i ; k++){
            System.out.print(" ");
         }
         for(int j = 1 ; j <= 2*i-1 ; j++){
            if(j == 1 || j == 2*i-1 || i == totalLevel){
               System.out.print("*");
            }else{
               System.out.print(" ");
            }
         }
            System.out.println("");
         }

化繁为简 => 先死后活

/**打印空心菱形
        *         *
        *       *   *
        *     *       *
        *       *   *
        *         *
        */
      int totalLevel = 7;
      for(int i = 1; i <= (totalLevel+1)/2 ; i++){
         for(int k = 1; k <= (totalLevel+1)/2-i ; k++){
            System.out.print(" ");
         }
         for(int j = 1 ; j <= 2*i-1 ; j++){
            if(j == 1 || j == 2*i-1){
               System.out.print("*");
            }else{
               System.out.print(" ");
            }
         }
            System.out.println();
         }
      for(int i = (totalLevel+1)/2+1; i <= totalLevel ; i++){
         for(int k = 1; k <= i - (totalLevel+1)/2 ; k++){
            System.out.print(" ");
         }
         for(int j = 1 ; j <= 2*(totalLevel - i)+1 ; j++){
            if(j == 1 || j == 2*(totalLevel - i)+1){
               System.out.print("*");
            }else{
               System.out.print(" ");
            }
         }
         System.out.println();
      }

4、break(跳转控制语句)

基本语法:

break语句用于终止某个语句块的执行,一般使用在switch或者循环中

{

……

break;

……

}

for(int i = 0;i < 10 ;i++){
        if(i == 3){
           break;//跳出for循环
        }
        System.out.println("i = " + i);
      }

break注意事项:

break语句出现在多层嵌套的语句块时,可以通过标签注明要终止的是哪一层语句块

标签的使用:

label1:{

label2:        {

label3:                {

                        break label2;

                }

        }

}

  • break语句可以指定退出哪层
  • label1是标签,由程序员指定
  • break后指定到哪个label就退出到哪里
  • 在实际的开发中,尽量不要使用标签
  • 如果没有指定break,默认退出最近的循环体
      label1:
      for(int i = 0;i < 4 ;i++){
      label2:
            for(int j = 0;j < 10 ;j++){
               if(j == 2){
                  break label1;
               }
               System.out.println("j = "+ j);
            }
      }

登录用户名与密码比较(三次机会)

      String user = "ABC";
      String key = "abc123";

      String name = "";
      String passWord = "";
      int chance = 3;
      Scanner sc = new Scanner(System.in);
      //输入部分
      for (int i = 1; i <= 3; i++) {//三次机会
         System.out.print("Enter your name: ");
         name = sc.nextLine();
         System.out.print("Enter your password: ");
         passWord = sc.nextLine();
         //比较部分:比较字符串方法:equals()方法
         //equals()方法中,实际字符串.equals(输入的要比较的字符串) 这种方法更好【避免空指针】
         if (user.equals(name) && key.equals(passWord)) {//字符串内容比较
            System.out.println("You have successfully logged in!");
            break;//结束for循环
         }
            chance--;//机会减一
            System.out.println("登陆失败!");
            System.out.println("你还有" + chance + "次登陆机会");
      }

5、continue

  • continue语句用于结束本次循环,继续执行下一次循环
  • continue语句出现在多层嵌套的循环语句时,可以通过标签指明要跳过的是哪一层循环,这个和前面的标签使用是一样的

基本语法:

{……

continue;

……

}

continue流程图(以while循环为例)

示例代码:

 int i = 1;
      while( i <= 4 ){
         i++;
         if( i == 2 ){
            continue;
         }
         System.out.println("i = "+i);
      }
     label1:
      for(int j = 0; j < 4 ; j++){
         System.out.println(j);
        label2:
         for(int i = 0; i < 10 ; i++){
            if(i == 2){
               continue;//结束i==2的内层循环
               //continue label1;//i==2时,结束当前外层label的循环
               //continue label2;//等价于continue
            }
            System.out.println("i = " + i);
         }
     }

6、return

return使用在方法,表示跳出所在的方法(如果return写在main方法,退出程序)

public static void main(String[] args) {
    for(int i = 1; i <= 5; i++){
       if(i == 3){
          System.out.println(i);
          return;//退出程序 没有输出go on
          //continue;//结束当次循环
          //break;//结束for循环,输出了go on
       }
       System.out.println("Hello,World");
    }
    System.out.println("go on……");
   }

三、学习总结:

本次学习中,主要学习的部分为控制结构

包括顺序、分支、循环等控制结构以及break、continue、return等跳转控制的关键字

其中,循环部分以及三个关键字较为重要

  • 18
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值