Java流程控制

Java流程控制

用户交互Scanner

通过Scanner类来获取用户的输入

基本语法:

Scanner s = new Scanner(System.in);

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

next():

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

nextLine():

  1. 以Enter为结束符,也就是说,nextLine()方法返回的是输入回车之前的所有字符
  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);
        }
        //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关闭
        scanner.close();

    }
}
import java.util.Scanner;

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();
            System.out.println("输入的内容为:"+str);
        }
        scanner.close();
    }
}

进阶使用

import java.util.Scanner;

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

顺序结构

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

public class ShunXuDemo01 {
    public static void main(String[] args) {
        System.out.println("gy01");
        System.out.println("gy02");
        System.out.println("gy03");
        System.out.println("gy04");
        System.out.println("gy05");
    }
}

选择结构

if单选择结构

判断一个东西是否可行,再去执行

语法:

if (布尔表达式){
	//如果布尔表达式为true将执行的语句
}
import java.util.Scanner;

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双选择结构

语法:

if (布尔表达式){
	//如果布尔表达式为true将执行的语句
}else{
	//如果布尔表达式为false将执行的语句
}
import java.util.Scanner;

public class IfDemo02 {
    public static void main(String[] args) {
        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将执行的语句
}
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){
            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 (布尔表达式1){
	//如果布尔表达式1为true将执行的语句
	if (布尔表达式2){
	//如果布尔表达式2为true将执行的语句
	}
}

switch多选择结构

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

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

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

switch语句中的变量类型可以是:

  1. byte.short.int或者char
  2. 从Java SE 7开始,switch支持字符串String类型了
  3. 同时case标签必须为字符串常量或字面量
public class SwitchDemo01 {
    public static void main(String[] args) {
        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 = "gy";
        switch (name){
            case "gy":
                System.out.println("gy");
                break;
            case "yg":
                System.out.println("yg");
                break;
            default:
                System.out.println("你干嘛!");
        }
    }
}

循环结构

while循环

while是最基本的循环

语法:

while (布尔表达式){
	//循环内容
}
//输出1~100
public class WhileDemo01 {
    public static void main(String[] args) {
        int i = 0;
        while (i<100){
            i++;
            System.out.println(i);
        }
    }
}

do...while循环

对于while语句而言,如果不满足条件,则不能进入循环

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

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

语法:

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

while和do...while的区别:

  1. while先判断后执行,do...while先执行后判断
  2. do...while总是保证循环体至少会被执行一次
public class DoWhileDemo01 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        do {
            sum = sum+i;
            i++;
        }while(i<=100);
        System.out.println(sum);
    }
}

for循环

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

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

语法:

for (初始化;布尔表达式;更新){
	//代码语句
}
public class ForDemo01 {
    public static void main(String[] args) {
        int i = 1;//初始化条件
        while (i<=100){//条件判断
            System.out.println(i);//循环体
            i+=2;//迭代
        }
        System.out.println("while循环结束!");

        for (int j=1;j<=100;j++){
            System.out.println(j);
        }
        System.out.println("for循环结束!");
    }
}

练习:

//计算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);
        System.out.println("偶数和为:"+evenSum);
    }
}
//用while或for循环输出1~1000之间的能被5整除的数,并且每行输出3个
public class ForDemo03 {
    public static void main(String[] args) {
        for (int i = 1; i <= 1000; i++) {
            if (i%5==0){
                //print 输出完不换行
                System.out.print(i+"\t");
            }
            if (i%(5*3)==0){
                //println 输出完会换行
                System.out.println();
            }

        }
    }
}
//打印九九乘法表
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(i+"*"+j+"="+(i*j)+"\t");
            }
            System.out.println();
        }
    }
}

增强for循环

语法:

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

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

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

public class ForDemo05 {
    public static void main(String[] args) {
        //定义一个数组
        int[] numbers = {10,20,30,40,50};
        for (int i = 0; i < 5; i++) {
            System.out.println(numbers[i]);
        }
        System.out.println("===========");
        //遍历数组中的元素
        for (int x:numbers){
            System.out.println(x);
        }
    }
}

break&continue

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

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

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

public class BreakDemo01 {
    public static void main(String[] args) {
        int i = 0;
        while (i<100){
            i++;
            System.out.println(i);
            if (i==30){
                break;
            }
        }
    }
}
public class ContinueDemo01 {
    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);
        }
    }
}

练习

//打印三角形 5行
public class TestDemo01 {
    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();
        }
    }
}
posted @   郭岩不会打代码  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示