4.Java流程控制

用户交互Scanner

java.util.Scanner是Java5的新特征,我们可以通过工具类(Scanner类)来获取用户的输入

基本语法:

Scanner s = new Scanner(System.in);

通过Scanner类的next()、nextLine()、nextInt()、nextFloat()等方法获取输入的数据,在读取前我们一般需要使用hasNext()、hasNextLine()、hasNextInt()、hasNextFloat()等方法判断是否还有输入的数据。

  • next()

    1. 一定要读取到有效字符后才可以结束输入。

    2. 输入有效字符之前遇到的空白,next()方法会自动将其去掉。

    3. 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。

    4. next()不能得到带有空格的字符串。

      next()方法使用示例:

      import java.util.Scanner;
      
      public class Demo {
          public static void main(String[] args) {
              //创建一个扫描器对象,用于接受键盘数据
              Scanner scanner = new Scanner(System.in);
      
              System.out.println("使用next方式接收:");
      
              //判断用户有没有输入字符串
              if(scanner.hasNext()) { //这里没有循环,其实可以去除
                  //使用next方式接收输入的字符串
                  String str = scanner.next(); //程序会等待用户输入完毕
                  System.out.println("输出的内容为:"+str);
              }
      
              //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
              //为了自己不会忘记关闭scanner,最好先加上scanner.close(),再写中间的代码。
              scanner.close();
          }
      
      }
      
      //该方法执行,输入"hello world",输出的结果为"hello"
      
  • nextLine()

    1. 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符

    2. 可以获得空白

      nextLine()方法使用示例:

      import java.util.Scanner;
      
      public class Demo {
          public static void main(String[] args) {
              //创建一个扫描器对象,用于接受键盘数据
              Scanner scanner = new Scanner(System.in);
      
              System.out.println("使用nextLine方式接收:");
      
              //判断用户有没有输入字符串
              if(scanner.hasNextLine()) { //这里没有循环,其实可以去除
                  //使用nextLine方式接收输入的字符串
                  String str = scanner.nextLine(); //程序会等待用户输入完毕
                  System.out.println("输出的内容为:"+str);
              }
      
              //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
              //为了自己不会忘记关闭scanner,最好先加上scanner.close(),再写中间的代码。
              scanner.close();
          }
      }
      
      //该方法执行,输入"hello world",输出的结果为"hello world"
      
  • nextInt()和nextFloat()

    nextInt()和nextFloat()使用示例:

    import java.util.Scanner;
    
    public class Demo {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            //从键盘接收数据
            int i = 0;
            float f = 0.0f;
    
            System.out.println("请输入整数:");
    
            if(scanner.hasNextInt()) {
                i = scanner.nextInt();
                System.out.println("整数数据:"+i);
            }else{
                System.out.println("输入的不是整数数据!");
            }
    
            System.out.println("请输入小数:");
    
            if(scanner.hasNextFloat()) {
                f = scanner.nextFloat();
                System.out.println("小数数据:"+f);
            }else{
                System.out.println("输入的不是小数数据!");
            }
    
            scanner.close();
        }
    }
    
    
  • Scanner类简单应用案例

    输入多个数字,求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入,并输出执行结果。

    import java.util.Scanner;
    
    public class Demo {
        public static void main(String[] args) {
    
            //输入多个数字,求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入,并输出执行结果。
            Scanner scanner = new Scanner(System.in);
    
            //和
            double sum = 0;
            //计算输入了多少个数字
            int m = 0;
    
            System.out.println("请输入数据:");
    
            //通过循环判断是否还有输入,并在里面对每一次进行求和和统计。
            while (scanner.hasNextDouble()) {
                double x = scanner.nextDouble();
                m++; // m = m + 1;
                sum += x; // sum = sum + x;
                System.out.println("你输入了第"+m+"个数据,当前结果sum为"+sum);
            }
    
            System.out.println(m+"个数的和为:"+sum);
            System.out.println(m+"个数的平均值为:"+(sum/m));
    
            scanner.close();
        }
    }
    
    

顺序结构

  • JAVA的基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行。
  • 顺序结构是最简单的算法结构。
  • 语句与语句之间,框与框之间是按从上到下的顺序进行的,它是由若干个依次执行的处理步骤组成的,它是任何一个算法都离不开的一种基本算法结构

程序流程图-顺序结构

代码:

public class ShunXuDemo {
    public static void main(String[] args) {
        System.out.println("hello1");
        System.out.println("hello2");
        System.out.println("hello3");
        System.out.println("hello4");
        System.out.println("hello5");
    }
}

选择结构

if单选择结构

我们很多时候需要去判断一个东西是否可行,然后我们才去执行,这样一个过程在程序中用if语句来表示。

语法:

if(布尔表达式){
	//如果布尔表达式为true将执行的语句
}

程序流程图-if单选择结构

代码:

import java.util.Scanner;

public class IfDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入内容:");
        String s = scanner.nextLine();

        //equals:判断字符串是否相等
        //注意:判断字符串是否相等最好不要用"=="
        if(s.equals("hello")){
            System.out.println(s);
        }
        System.out.println("end");
        scanner.close();
    }
}

if双选择结构

现在有个需求,公司购买一个软件,成功了,给人支付100万元,失败了,自己找人开发。这样的需求用一个if就搞不定了,我们需要有两个判断,需要一个双选择结构,所以就有了if-else语句

语法:

if(布尔表达式){
	//如果布尔表达式的值为true
}else{
	//如果布尔表达式的值为false
}

程序流程图-if双选择结构

代码:

import java.util.Scanner;

public class IfDemo {
    public static void main(String[] args) {
        //考试分数大于60分就是及格,小于60分就是不及格。
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入成绩:");
        int score = scanner.nextInt();
        if (score > 60) {
            System.out.println("及格");
        }else {
            System.out.println("不及格");
        }
        scanner.close();
    }
}

if多选择结构

在生活中我们很多时候的选择不仅仅只有两个,所以我们需要一个多选择结构来处理这类问题。

语法:

if(布尔表达式1){
	//如果布尔表达式1的值为true执行代码
}else if(布尔表达式2){
	//如果布尔表达式2的值为true执行代码
}else if(布尔表达式3){
	//如果布尔表达式3的值为true执行代码
}else {
    //如果以上布尔表达式都不为true执行代码
}

程序流程图-if多选择结构

代码:

import java.util.Scanner;

public class IfDemo {
    public static void main(String[] args) {
        //考试分数大于60分就是及格,小于60分就是不及格。
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入成绩:");
        int score = scanner.nextInt();
        /**
         if语句至多有1个else语句(可以没有!),eLse语句在所有的else if 语句之后。
         if语句可以有若干个else if语句,它们必须在else语句之前。
         一旦其中一个else if语句检测为true,其他的else if以及else语句都将跳过执行。
         */
        if (score == 100) {
            System.out.println("恭喜满分");
        }else if (score < 100 && score >= 90){
            System.out.println("A级");
        }else if (score < 90 && score >= 80){
            System.out.println("B级");
        }else if (score < 80 && score >= 70){
            System.out.println("C级");
        }else if (score < 70 && score >= 60){
            System.out.println("D级");
        }else if (score < 60 && score >= 0){
            System.out.println("不及格");
        }else{
            //程序一定要严谨
            System.out.println("成绩不合法!");
        }
        scanner.close();
    }
}

嵌套的if结构

使用嵌套的 if...else 语句是合法的。也就是说你可以在另一个 if 或者 else if 语句中使用 if 或者 else if 语句。你可以像 if 语句一样嵌套 else if...else

语法:

if(布尔表达式1){
	//如果布尔表达式1的值为true执行代码
    if(布尔表达式2){
        //如果布尔表达式2的值为true执行代码
    }
}

switch多选择结构

  • 多选择结构还有一个实现方式就是switch case语句
  • switch case语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支
  • switch语句中的变量类型可以是:
    • byte、short、int或者char
    • 从Java SE 7开始,switch支持字符串String类型了。
    • 同时case标签必须为字符串常量或字面量

语法:

switch(expression){
	case value :
		//语句
		break;//可选
    case value :
        //语句
		break;//可选
	//你可以有任意数量的case语句
    default : //可选
		//语句
}

代码:

public class SwitchDemo01 {
    public static void main(String[] args) {
        //case穿透现象
        //case语句最后如果没有加break,程序会一直往后执行,直到遇到break或者把整个switch语句中所有的代码全部执行完了,才会结束。
        char grade = 'C';
        switch (grade) {
            case 'A':
                System.out.println("优秀");
                break;
            case 'B':
                System.out.println("良好");
            case 'C':
                System.out.println("及格");
            case 'D':
                System.out.println("再接再厉");
                break;
            case 'E':
                System.out.println("挂科");
            default:
                System.out.println("未知等级");
        }
    }
}
public class SwitchDemo02 {
    public static void main(String[] args) {
        String name = "麻辣烫";
        //JDK7的新特性,表达式结果可以是字符串!!!
        //字符的本质还是数字
        //反编译:java代码-->class(字节码文件)-->反编译(用IDEA打开)
        switch (name) {
            case "凉皮":
                System.out.println("凉皮");
                break;
            case "麻辣烫":
                System.out.println("麻辣烫");
                break;
            case "螺蛳粉":
                System.out.println("螺蛳粉");
                break;
            default:
                System.out.println("未知");

        }
    }
}

循环结构

while循环

while循环是最基本的循环。

语法:

while (布尔表达式){
    //循环内容
}
  • 只要布尔表达式为true,循环就会一直执行下去。
  • 我们大多数情况是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。
  • 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
  • 循环条件一直为true就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死奔溃!

代码:

public class WhileDemo {
    public static void main(String[] args) {
        //输出1-100
        int i = 0;
        while (i < 100) {
            i++;
            System.out.println(i);
        }
        
        //计算1+2+3+...+100=?
        int num = 1;
        int sum = 0;
        while (num <= 100) {
            sum = sum + num;
            num++;
        }
        System.out.println(sum); //输出5050
    }
}

do while循环

语法:

do {
    //代码语句
}while(布尔表达式);
  • 对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。

  • do while循环和while循环相似,不同的是,do while循环至少会执行一次。

  • while和do while的区别:

    while先判断后执行,do while先执行后判断。

    do while总是保证循环体会被至少执行一次!这是他们的主要差别。

代码:

public class DoWhileDemo {
    public static void main(String[] args) {
        int a = 0;
        while (a < 0){
            System.out.println(a);
            a++;
        }
        System.out.println("=================");
        do {
            System.out.println(a);
            a++;
        } while (a < 0);
    }
}
//执行结果:while的循环体没有执行,do while的循环体执行了一次,输出0。

for循环

  • 虽然所有循环结构都可以用while或者do while表示,但Java提供了另一种语句——for循环,使一些循环结构变得更加简单。
  • for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构
  • for循环执行的次数是在执行前就确定的。

语法:

for(初始化;布尔表达式;更新){
    //代码语句
}

代码:

public class ForDemo01 {
    public static void main(String[] args) {
        int a = 1; //初始化条件

        while (a <= 100) { //条件判断
            System.out.println(a); //循环体
            a += 2; //迭代
        }

        System.out.println("while循环结束!");

             //初始化值  //条件判断 //迭代
        for (int i = 1; i <= 100; i++) {
            System.out.println(i); //循环体
        }
        //for循环快捷键:100.for+回车

        System.out.println("for循环结束");

        /*
        * 关于for循环有以下几点说明:
        * 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
        * 然后,检测布尔表达式的值。如果为true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
        * 执行一次循环后,更新循环控制变量(迭代因子控制循环变量的增减)。
        * 再次检测布尔表达式,循环执行上面的过程。
        */
        
        //死循环
        for ( ; ; ) {

        }
    }
}

public class ForDemo02 {
    public static void main(String[] args) {
        //练习1:计算0到100之间的奇数和偶数的和。
        int oddSum = 0; //奇数和
        int evenSum = 0; //偶数和
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) { //奇数
                oddSum += i;
            }else{ //偶数
                evenSum += i;
            }
        }
        System.out.println("奇数的和:"+oddSum);
        System.out.println("偶数的和:"+evenSum);
    }
}
public class ForDemo03 {
    public static void main(String[] args) {
        //练习2:用while或for循环输出1-1000之间能被5整除的数,并且每行输出三个。
        for (int i = 1; i <= 1000; i++) {
            if (i % 5 == 0) {
                System.out.print(i+"\t");
            }
            if (i % (5 * 3) == 0) {
                System.out.print("\n"); // 换行
                //等于System.out.println();
            }
        }

        System.out.println("for循环结束!");

        //println 输出完会换行
        //print 输出完不会换行

        int i = 1;
        while (i <= 1000) {
            if (i % 5 == 0) {
                System.out.print(i+"\t");
            }
            if (i % (5 * 3) == 0) {
                System.out.print("\n"); // 换行
                //等于System.out.println();
            }
            i++;
        }
        System.out.println("while循环结束!");
    }
}
public class ForDemo04 {
    public static void main(String[] args) {
        /*
         练习3:打印九九乘法表。
         1*1=1
         1*2=2	2*2=4
         1*3=3	2*3=6	3*3=9
         1*4=4	2*4=8	3*4=12	4*4=16
         1*5=5	2*5=10	3*5=15	4*5=20	5*5=25
         1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36
         1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49
         1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64
         1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81
        */
        //拆分问题,逐步解决
        //1.先打印第一列
        //2.把固定的1再用一个循环包起来
        //3.去掉重复项,j <= i
        //4.调整样式
        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 = 9; i >= 1 ; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
            }
            System.out.println();
        }
    }
}

增强for循环

在Java5中引入了一种主要用于数组或集合的增强型for循环

java增强for循环语法:

for(声明语句:表达式)
{
   //代码句子
}
  • 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
  • 表达式:表达式是要访问的数组名,或者是返回值为数组的方法

代码:

public class ForDemo05 {
    public static void main(String[] args) {

        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //定义一个数组

        //使用基础for循环遍历数组的元素
        int len = numbers.length; //数组长度
        for (int i = 0; i < len; i++) {
            System.out.println(numbers[i]);
        }

        System.out.println("===============");

        //使用增强for循环遍历数组的元素
        for (int x:numbers){
            System.out.println(x);
        }
    }
}

break continue goto

  • break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break语句也在switch语句中使用)
  • continue语句用在循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。
  • 关于goto关键字
    • goto关键字很早就在程序设计语言中出现。尽管goto仍是Java的一个保留字,但并未在语言中得到正式使用;Java没有goto。然而,在break和continue这两个关键字的身上,我们仍然能看出一些goto的影子——带标签的break和continue。
    • “标签”是指后面跟一个冒号的标识符,例如 :" label:"。
    • 对Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望在其中嵌套另一个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。

break代码:

public class BreakDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            System.out.println(i);
            if (i == 30) {
                break;
            }
        }
    }
}

continue代码:

public class ContinueDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            if (i % 10 == 0) {
                System.out.println();
                continue;
            }
            System.out.print(i + " ");
        }
    }
}

标签代码:

public class LabelDemo {
    public static void main(String[] args) {
        //打印101-150之间所有的质数
        //质数是指大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。
        outer:for (int i = 101; i <= 150; i++) {
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    continue outer;
                }
            }
            System.out.print(i + " ");
        }
    }
}

流程控制练习

打印三角形

代码:

public class TextDemo {
    public static void main(String[] args) {
       //打印三角形 5行
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            for (int j = 1; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        
        //可以利用IDEA的Debug工具查看程序每一步变量值的变化
    }
}
posted @ 2024-08-09 16:09  爱吃麻辣烫的妹纸  阅读(4)  评论(0编辑  收藏  举报