Java流程控制

Java流程控制

一.用户交互scanner

通过scanner类来获取用户输入

基本语法:

Scanner s = new Scanner(System.in)

1.字符串的输入

通过scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。

next():

  1. 一定要读取到有效字符后才可以结束
  2. 对输入有效字符之前遇到的空白,next()方法会自动将其去掉
  3. 只有输入有效字符后,才将后面的输入的空白作为分隔符或者结束符
  4. next()不能得到带有空格的字符串

nextLine():

  1. 以Enter为结束符,也就是说next Line()方法返回的是输入回车之前的所有字符
  2. 可以获取空白

代码练习:

import java.util.Scanner;
public class Demo01 {
    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);
        }
        /*System.out.println("使用nextLine接收");
        //判断用户有没有输入字符串
        if (scanner.hasNextLine()){
        //使用nextLine方式接收
            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);
        }*/
        //凡是IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
        scanner.close();
    }
}

2.sanner的进阶使用

判断:scanner.hasNextInt (); scanner.hasNextFloat (); scanner.hasNextDouble ();等

获取:scanner.nextInt(); scanner.nextFloat (); scanner.nextDouble ();等

import java.util.Scanner;
public class Demo02 {
    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();
    }
}

import java.util.Scanner;
public class Demo03 {
    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++;
            sum+=x;
            System.out.println("你输入了第"+m+"个数据,当前结果为sum="+sum);
        }
        System.out.println(m+"个数的和为:"+sum);
        System.out.println(m+"个数的平均值为:"+(sum/m));
        scanner.close();
    }
}

二.顺序结构

Java基本结构就是顺序结构,除非特别指明,否则就按照顺序一句一句执行,顺序结构是最简单的算法结构。

三.选择结构

1.if选择结构

if单选择结构:

判断一个东西是否执行,然后才去执行,这样一个过程在程序中使用if语句。

语法:

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

流程图:

在这里插入图片描述

代码练习:

import java.util.Scanner;
public class IfDemo01 {
    public static void main(String[] args) {
        System.out.println("请输入内容:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        //equals:判断字符串是否相等
        if (s.equals("Hello")){
            System.out.println(s);
        }
        System.out.println("End");
        scanner.close();
    }
}

2.if双选择结构

有两个判断时,使用if-else语句

语法:

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

流程图:

在这里插入图片描述

代码练习:

import java.util.Scanner;
public class IfDemo02 {
    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();
    }
}

3.if多选择结构

选择不仅仅只有两个时,使用多选择结构。

语法:

if (布尔表达式1){
    //如果布尔表达式为true将执行的语句
}else if (布尔表达式2){
    //如果布尔表达式true将执行的语句
}else if (布尔表达式3){
    //如果布尔表达式true将执行的语句
}else{
    //如果以上布尔表达式不为true将执行的语句
}

流程图:

在这里插入图片描述

代码练习:

import java.util.Scanner;
public class IfDemo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入成绩:");
        int score = scanner.nextInt();
        if (score==100){
            System.out.println("恭喜满分");
        }else if (score<100 && score>90){
            //这里使用if嵌套语句
            if(score>95){
                System.out.println("超级优秀");
            }else{
                System.out.println("优秀");
            }
            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();
    }
}

4.switch多选择结构

多选择结构还有一个实现方式就是switch case 语句。

Switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。

switch 中的变量类型可以是:

  • byte、short、int 、char
  • 从Java SE7 开始支持字符串string类型了,同时case标签必须为字符串常量或字面量

语法:

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

代码练习:

import java.util.Scanner;
public class SwitchDemo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        //JDK7新特性,表达式的结果可以是字符串
        //字符的本质还是数字
        switch (name){
            case "秦疆":
                System.out.println("秦疆");
                break;
            case "狂神":
                System.out.println("狂神");
                break;
            default:
                System.out.println("错误");
        }
    }
}

这里讲一个反编译方法:

​ //反编译 java—class(字节码文件)-----反编译(IDEA)
​ //项目结构—找到output路径(复制)----去计算机找到class文件(复制)
​ //在编写代码这边的目录下-----鼠标右击“show in Explorer"–将class文件复制进去
​ //在目录下可以打开查看class文件

四.循环结构

1.while循环结构

while是最基本的循环

语法:

while (布尔表达式){
    //循环内容
}

只要布尔表达式为true,循环就会一直执行下去。

我们大多数情况下会让循环停止下来,需要一个让表达式失效的方式来结束循环

少部分情况需要让循环一直执行,比如服务器的请求响应监听等。

循环条件一直为true就会造成无限循环我们正常的业务编程中应该尽量避免死循环,会影响程序性能或者造成程序卡斯奔溃。

代码练习:

public class WhileDemo01 {
    public static void main(String[] args) {
        //输出1~100
        int i = 0;
        while (i<100){
            i++;
            System.out.println(i);
        }
    }
}

public class WhileDemo02 {
    public static void main(String[] args) {
        //死循环
        while (true){
            //等待客户端连接
            //定时检查
            //....
        }
    }
}

2.do while循环

有时候我们需要即使不满足条件,也至少执行一次。

do…while循环与while循环相似,不同的是,do…while循环至少执行一次。

语法:

do {
    //代码语句
}while (布尔表达式)

两者区别:

  • while先判断后执行,do…while先执行后判断

  • do… while总是保证循环至少被执行一次

  • 执行完一次后,do…while 与while循环一样,判断布尔表达式决定是否执行循环内容


代码练习:

public class DoWhileDemo01 {
    public static void main(String[] args) {
        int a = 1;
        while (a<0){
            System.out.println(a);//不满足布尔表达式,不执行
            a++;
        }
        System.out.println("=============");
        do{
            System.out.println(a);//执行一次,输出结果为:1
            a++;
        }while (a<0);
    }
}

3.for 循环

for循环是支持迭代的一种通用结构,是最有效、最灵活的循环结构。

for循环执行的次数是在执行前就确定的。

语法:

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

声明:

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

代码:

public class ForDemo01 {
    public static void main(String[] args) {
        for (int i=1;i<=100;i++){
            System.out.println(i);
        }
        //快捷键  如:100.for
        System.out.println("for循环结束");
        
        //与while循环进行比较
        /*int a = 1;//初始化条件
        while (a<=100){//条件判断
            System.out.println(a);//循环体
            a += 2;//迭代
        }
        System.out.println("while循环结束");*/
        //初始化;判断;迭代
        
        /**空循环
         * for(; ; ){
         * }
         */
    }
}

for循环结构中可以嵌套其他结构

代码练习:

public class ForDemo02 {
    public static void main(String[] args) {
        //练习:用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.println();
                //System.out.print("\n");
            }
        }
        //println  输出完会换行
        //print  输出完不会换行
    }
}

4.打印九九乘法表

for—for循环结构:

public class ForDemo04 {
    public static void main(String[] args) {
        //练习3:打印九九乘法表
        //1.打印第一列
        //2.把固定的1再用一个循环包起来
        //3.去掉重复项
        //4.调整样式
        for (int i = 1; i <= 9; i++) {
            for (int j =1;j<=i;j++){
                System.out.print(j+"*"+i+"="+(i*j));
                System.out.print("\t");
            }
            System.out.println();
        }
    }
}

for—while 循环结构:

public class ForDemo06 {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            int j = 1;
            while (j<=i){
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
                j++;
            }
            System.out.println();
        }
    }
}

while—for 循环结构:

public class ForDemo05 {
    public static void main(String[] args) {
        int i = 1;
        while (i<=9){
            for (int j = 1;  j<= i; j++) {
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
            }
            i++;
            System.out.println();
        }
    }
}

while—while 循环结构:

public class WhileDemo04 {
    public static void main(String[] args) {
        int i =1;
        while (i<=9){
            int j =1;
            while (j <=i ){
                System.out.print(j+"*"+i+"="+(i*j)+"\t");
                j++;
            }
            i++;
            System.out.println();
        }
    }
}

5.增强for循环

先做了解,数组中会重点使用。

语法:

for (声明语句:表达式)
{
    //代码语句
}

声明语句:声明新的局部变量,该变量类型必须和数组元素的类型相匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。

表达式:表达式是要访问的数组名,或者是返回值为数组的方法

代码练习:

public class ForDemo07 {
    public static void main(String[] args) {
        int[] number = {10,20,30,40,50};//定义一个数组

        for (int i = 0; i < 5; i++) {
            System.out.println(number[i]);
        }
        System.out.println("===============");
        //遍历数组的元素
        for (int x:number){
            System.out.println(x);
        }
    }
}

五.break、continue与goto

1.break

break在任何循环语句的主题部分,均可用break控制循环的流程。

break用于强制退出循环,不执行循环中剩余的语句(break语句也在switch语句中使用)

2.continue

continue语句用在循环语句中,用于终止某次循环的过程,即可跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定。


break看作”辞职“,continue看作”请假“


3.关于goto关键字

​ goto关键字很早就在程序中出现。尽管goto仍然是Java的一个保留字,但并未在语言中得到正式的使用;Java没有goto。然而,在break和continue这两个关键字的身上,我们仍能看到一些goto的影子-------带标签的break和continue。


标签是指后面跟一个冒号的标识符。例如: label:


对于Java来说唯一用到标签的地方是在循环语句之前。而在循环之前设置标签的唯一理由是:我们希望嵌套另一个循环,由于break和continue关键字通常只中断当前循环,但若随同标签使用,它们就会中断到存在标签的地方。

代码练习:

public class LabelDemo {
    public static void main(String[] args) { 
        //求101~150之间的质数
        int count = 0;
        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+" ");
            count++;
            if (count%3==0){
                System.out.println();//每三个数换行
            }
        }
    }
}

六.练习(打印三角形)及Debug调试

思想:使用每行输出叠加,首先我们想好三角形的大小,我们这里是利用for循环来实现,先画出每行的空白,再依次叠加图案即可。

打印三角形代码:

public class TestDemo01 {
    public static void main(String[] args) {
        //打印三角形  6行
        for (int i = 1; i <= 6; i++) {
            for (int j=6;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();
        }
    }
}

调试:

我们将显示代码行数那里使用鼠标,将需要停止的部分点击成红色,点击Debug,在运行栏那里可以进行步骤运行。这样我们便可以查看代码运行的步骤结果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值