Java流程控制

Java流程控制

1. 用户交互 Scanner

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

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        // 创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);

        //判断用户有没有输入字符串
        if(scanner.hasNext()){
            // 使用next方式接收
            String str=scanner.next();
            System.out.println("输出内容为:"+str);
        }
        // 凡是属于IO流的类如果不关闭就会一直占用资源,用完就关掉
        scanner.close();
    }
}
// nextLine()
import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        // 创建一个扫描器对象,用于接收键盘数据
        Scanner scanner = new Scanner(System.in);

        //判断用户有没有输入字符串
        if (scanner.hasNextLine()) {
            // 使用nextLine方式接收
            // 输入: Hello world,输出为:Hello world
            String str = scanner.nextLine();
            System.out.println("输出内容为:" + str);
        }
        // 凡是属于 IO流的类 如果不关闭就会一直占用资源,用完就关掉
        scanner.close();
    }

}
import java.util.Scanner;

public class Demo03 {
    public static void main(String[] args) {
        // 从键盘接收数据
        Scanner scanner = new Scanner(System.in);

        System.out.println("输入数据:");

        String str=scanner.nextLine();

        System.out.println("输出内容为:"+str);

        scanner.close();
    }
}
  • Scanner类的next() 与nextLine() 方法的区别

    next():对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉

    next() 后用 nextLint() ,nextLint() 会自动读取被next() 去掉的 Enter 作为它的结束符

    解决办法:在每一个 next()、nextDouble()、nextFlo()、nextInt() 等语句后加一个 nextLine() 语句,将被 next() 去掉的Enter等结束符过滤掉。

image-20220414094041443
  • 小练习

    package com.xueling.scanner;
    
    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+=1;
                sum+=x;
            }
            double avg=sum/m;
    
            System.out.println(m+"个数的和为"+sum);
            System.out.println(m+"个数的平均数为"+avg);
    
            scanner.close();
        }
    }
    

2.顺序结构

Java基本结构为顺序结构,程序从上往下执行。

import java.util.Scanner;

public class Demo01_if {
    public static void main(String[] args) {
        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();
    }
}

3.选择结构

1. if语句

// 嵌套
if(...){
    ...
}else if(...){
    ...
}else{
    ...
}

2. switch case语句

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

例子

public class SwitchDemo01 {
    public static void main(String[] args) {
        char grade = 'D';
        // 支持比较字符串   如:Strin name = "张三" ;
        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语句
            default:    // 可选
                // 语句
                System.out.println("未知等级");
        }
    }
}

4.循环结构

1.for 循环

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pew7tUmh-1649940968368)(image-20220414144034975.png)]

  • 练习
public class ForDemo01 {
    public static void main(String[] args) {
        // 打印九九乘法表
        for (int i = 1; i <= 9; i++) {
            for (int j=1;j<=i;j++){
                System.out.print(j+"x"+i+"="+(j*i)+"\t");
            }
            // 换行
            System.out.println();
            // System.out.print("\n");
        }
    }
}
  • 增强for循环:主要用于数组和集合
public class ForDemo02 {
    public static void main(String[] args) {
        // 定义一个数组
        int[] numbers = {10, 20, 30, 40};
        for (int num : numbers) {
            System.out.println(num);
        }

    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rY7bRrvP-1649940968369)(image-20220414154137569.png)]

2.while 循环

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-exLLXQRD-1649940968370)(image-20220414143123243.png)]

  • 练习
public class WhileDemo {
    public static void main(String[] args) {
        int i=0;
        int sum=0;
        while (i<=100){
            // i++ 放在这里会有问题
            sum+=i;
            i++;
        }
        System.out.println(sum);
    }
}

3.do…while 循环

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mjHX0Lgd-1649940968371)(image-20220414143157494.png)]

  • 练习
public class DoWhile {
    public static void main(String[] args) {
        int i=0;
        int sum=0;
        do{
            // i++ 放在这里会有问题
            sum+=i;
            i++;
        }while (i<=100);
        System.out.println(sum);
    }
}

5. Java 方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IhMKh12s-1649940968373)(image-20220414161729831.png)]

1. 定义一个类方法

// public、static 是修饰符,static 表示为类的变量或方法
// void 方法没有返回值,返回为空;int 方法返回值类型为 int 型

public class Demo01 {
    // main 方法
    public static void main(String[] args) {
        int add = add(1, 2);
        System.out.println(add);
    }

    // add 加法方法
    public static int add(int x,int y){
        return x+y;
    }
}

返回较大的值

public class Demo02 {
    public static void main(String[] args) {
        int a = max(6, 8);
        int b = max(9, 5);
        System.out.println(a);
        System.out.println(b);
    }

    public static int max(int x, int y) {
        return x > y ? x : y;
    }
}

Java 为值传递

2. 方法的重载

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YHxdQifV-1649940968374)(image-20220414192918923.png)]

3. 命令行传参

package com.xueling.method;

public class Demo03 {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            // 命令行 传参
            // 命令行编译,然后在src目录执行:java com.xueling.method.Dome03 hello world
            // 输出:args[0]:hello
            //     args[1]:world
            System.out.println("args["+i+"]:"+args[i]);
        }
    }
}

4. 可变参数

一个方法只能有一个可变参数,在参数类型后加省略号 ... ,可传入多个参数。只能放在最后面,为方法的最后一个参数,任何普通参数都必须在它前面声明

package com.xueling.method;

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

        printMax(25, 65, 12.9, 7, 56, 89, 147, 23, 56);
        printMax(new double[]{1, 3, 5, 8, 1.2, 68, 23});

    }

    public static void printMax(double... numbers) {
        if (numbers.length == 0) {
            System.out.println("No argument passed");
            return;
        }

        double result = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > result) {
                result = numbers[i];
            }
        }
        System.out.println("The max value is " + result);
    }
}

5. 递归

自己调用自己,尽量不用递归

package com.xueling.method;

import java.util.Scanner;

public class Demo05 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
		
        while (scanner.hasNextInt()) {
            int k = scanner.nextInt();
            int result = f(k);
            System.out.println(k + "!=" + result);
        }
    }
	// 求阶乘
    public static int f(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * (n - 1);
        }

    }
}

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

     while (scanner.hasNextInt()) {
         int k = scanner.nextInt();
         int result = f(k);
         System.out.println(k + "!=" + result);
     }
 }
// 求阶乘
 public static int f(int n) {
     if (n == 1) {
         return 1;
     } else {
         return n * (n - 1);
     }

 }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值