zoukankan      html  css  js  c++  java
  • Day003 Java流程控制

    Java流程控制

    Scanner

    • 作用:通过Scanner获取用户的输入

    • 基本语法:

    Scanner s = new Scanner(System.in);
    
    • 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据

    • 凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉

    Scanner scanner = new Scanner(System.in);
    scanner.close();
    
    • next():
    1. 一定要读取到有效字符后才可以结束输入
    2. 对输入有效字符之前遇到的空白,next()方法会自动将其去掉
    3. 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
    4. next()不能得到带有空格的字符串
    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();			//hello world
                System.out.println("输出的内容为:" + str);//hello
            }
    
            //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
            scanner.close();
        }
    }
    
    • nextLine():
    1. 以Enter为结束符,nextLine()方法返回的是输入回车之前的所有字符
    2. 可以获得空白
    public class Demo02 {
        public static void main(String[] args) {
            //从键盘接收数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("使用nextLine方式接收:");
    
            //判断是否还有输入
            if (scanner.hasNextLine()) {
                String str = scanner.nextLine();		//hello world
                System.out.println("输出的内容为:" + str);//hello world
            }
    
            scanner.close();
        }
    }
    
    例子1
    public class Demo01 {
        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();
        }
    }
    
    例子2
    public class Demo02 {
        public static void main(String[] args) {
            //输入多个数字,求其总和与平均数,每输入一个数字用回车去人,通过输入非数字来结束输入并输出执行结果
            Scanner scanner = new Scanner(System.in);
            //和
            double sum = 0;
            //计算输入了多少个数字
            int m = 0;
            //通过循环判断是否还有输入,并在里面对每一次进行求和和统计
            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();
        }
    }
    

    顺序结构

    • 一句一句执行
    • 顺序结构是最简单的算法结构
    • 它是任何一个算法都离不开的一种基本算法结构

    If选择结构

    单选择结构

    • 作用:判断一个东西是否可行,然后去执行
    • 基本语法:
    if(布尔表达式){
    	//如果布尔表达式为true将执行的语句
    }
    
    public class IfDemo01 {
        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(布尔表达式){
    	//如果布尔表达式为true将执行的语句
    }else{
    	//如果布尔表达式为false将执行的语句
    }
    
    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();
        }
    }
    

    多选择结构

    • 作用:有时两种选择不够,实际需要应对多钟情况,例如将成绩10090分评为A,9080评为B,80~70评为C,等等......

    • 语法:

    if(布尔表达式 1){
    	//如果布尔表达式1为true将执行的语句
    }else if(布尔表达式 2){
        //如果布尔表达式2为true将执行的语句
    }else if(布尔表达式 3){
        //如果布尔表达式3为true将执行的语句
    }else{
    	//如果以上布尔表达式都为false将执行的语句
    }
    
    public class IfDemo03 {
        public static void main(String[] args) {
            //考试分数大于60分及格,小于60分不及格
            Scanner scanner = new Scanner(System.in);
    
            /*
            if语句至多有1个else语句,else语句在所有的else if语句后面
            if语句可以有若干个else if语句,它们必须再else语句之前
            一旦其中一个else if语句检测为true,其他的else if以及else语句就会跳过执行
             */
    
            System.out.println("请输入成绩:");
            int score = scanner.nextInt();
    
            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(布尔表达式 1){
    	//如果布尔表达式1为true将执行的语句
    	if(布尔表达式 2){
        	//如果布尔表达式2为true将执行的语句
    	}
    }
    

    Switch选择结构

    • 作用:判断一个变量与一系列值中某个值是否相等,每个值成为一个分支

    • 语法:

    switch(expression){
    	case value:
    		//语句
    		brreak;//可选
    	case value:
    		//语句
    		brreak;//可选
    	//可以有任意数量的case
    	default:	//可选
    		//语句
    }
    
    • switch语句中的变量类型可以是:
      • byte,short,int,char
      • 从JavaSE 7开始,switch支持字符串String类型
      • case标签必须为字符串常量或字面量
    public class SwitchDemo01 {
        public static void main(String[] args) {
            //case穿透:没有break的话会继续执行后面的case
            //switch 匹配一个具体的值
            char grade = 'C';
    
            switch (grade) {
                case 'A':
                    System.out.println("优秀");
                    break;//可选
                case 'B':
                    System.out.println("良好");
                    break;
                case 'C':
                    System.out.println("及格");
                    break;
                case 'D':
                    System.out.println("再接再厉");
                    break;
                case 'E':
                    System.out.println("挂科");
                    break;
                default:
                    System.out.println("未知等级");
            }
        }
    }
    
    public class SwitchDemo02 {
        public static void main(String[] args) {
            String name = "莉莉卡";
    
            //jdk7特性,表达式结果可以使是符串
            //字符的本质还是数字
            switch (name) {
                case "杰达鲁":
                    System.out.println("杰达鲁");
                    break;
                case "莉莉卡":
                    System.out.println("莉莉卡");
                    break;
                default:
                    System.out.println("未知名字");
                    break;
            }
        }
    }
    

    反编译

    • java->class(字节码文件)->反编译(IDEA)

    将out文件夹中的.class文件移入代码路径,在IDEA中打开即可查看反编译后的文件

    While循环

    • 作用:用于重复执行命令
    • 基本语法 :
    while(布尔表达式){
    	//循环内容
    }
    
    • 先判断条件,再进入循环执行内容

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

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

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

      正常业务编程中应该尽量避免死循环,会影响程序性能或者造成程序卡死崩溃

    计算1+2+3+...+100:

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

    Do...While循环

    • 先执行一遍内容,再判断条件
    • 至少会执行一次内容
    • 基本语法:
    do{
    	//循环内容
    }while(布尔表达式)
    
    public class DoWhileDemo02 {
        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);//输出0
                a++;
            } while (a < 0);
        }
    }
    

    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);
            }
            System.out.println("for循环结束");
            /*
                快捷键:输入100.for
                for (int i = 0; i < 100; i++) {}
             */
        }
    }
    

    增强For循环

    • 作用:主要用于数组或集合的增强型For循环
    • 基本语法:
    for(声明语句:表达式){
    	//循环代码
    }
    
    • 声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等
    • 表达式:表达式是要访问的数组名,或者是返回值为数组的方法
    public class ForDemo05 {
        public static void main(String[] args) {
            //定义一个数组
            int[] numbers = {10, 20, 30, 40, 50};
    
            //遍历数组的元素
            for (int x : numbers) {
                System.out.print(x+" ");//10 20 30 40 50
            }
            System.out.println("
    "+"------------");
            for (int i = 0; i < 5; i++) {
                System.out.print(numbers[i]+" ");//10 20 30 40 50
            }
        }
    }
    

    练习

    • 计算0到100之间的奇数和偶数的和
    public class ForDemo02 {
        public static void main(String[] args) {
            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);//2500
            System.out.println("偶数和:" + evenSum);//2550
        }
    }
    
    • 用while或for循环是输出1~100之间能被5整除的数,并且每行输出3个
    public class ForDemo03 {
        public static void main(String[] args) {
            for (int i = 1; i <= 1000; i++) {
                if (i % 5 == 0) {
                    System.out.print(i + "	");
                }
                if (i % (5 * 3) == 0) {
                    System.out.println();
                    //System.out.print("
    ");
                }
            }
    
            int j = 1;
            while (j <= 1000) {
                if (j % 5 == 0) {
                    System.out.print(j + "	");
                }
                if (j % (5 * 3) == 0) {
                    System.out.println();
                }
                j++;
            }
        }
    }
    
    • 打印九九乘法表
    public class ForDemo04 {
        public static void main(String[] args) {
            for (int i = 1; i <= 9; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(j + "*" + i + "=" + (j * i) + "	");
                }
                System.out.println();
            }
        }
    }
    

    break continue goto

    break

    • 在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。
    public class BreakDemo {
        public static void main(String[] args) {
            //i等于30时退出循环
            int i = 0;
            while (i < 100) {
                i++;
                System.out.println(i);
                if (i == 30) {
                    break;
                }
            }
            System.out.println("结束");
        }
    }
    

    continue

    • continue用于循环语句体中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着进行下一次是否执行循环的判定
    public class ContinueDemo {
        public static void main(String[] args) {
            //不输出10的倍数
            int i = 0;
            while (i < 100) {
                i++;
                if (i % 10 == 0) {
                    System.out.println();
                    continue;
                }
                System.out.print(i + "	");
            }
        }
    }
    

    goto

    • goto是Java的一个保留字,但并未在语言中得到正式使用。但在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; j++) {
                    if (i % j == 0) {
                        continue outer;
                    }
                }
                System.out.print(i + " ");
            }
        }
    }
    

    练习

    • 打印5行三角形
    public class TestDemo {
        public static void main(String[] args) {
            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();
            }
        }
    }
    
  • 相关阅读:
    Ubuntu 出现 apt-get问题的解决方法
    Conversion to Dalvik format failed: Unable to execute dex: null
    java中判断是否为中文
    解决:Unable to connect to repository https://dl-ssl.google.com/android/eclipse/site.xml
    Android 获取本机WIFI及3G网络IP
    xp重装系统后恢复Linux启动
    Android中空格及换行
    ubuntu12.10设置thunderbird开机自启动
    web安全及防护
    回归基础: JavaScript 变量提升
  • 原文地址:https://www.cnblogs.com/mooncell/p/14518437.html
Copyright © 2011-2022 走看看