Java循环结构、Scanner、数组

157 阅读5分钟

顺序结构

按照顺序一步一步执行。一路直下

选择结构

if语句
if-else语句

public class IfElseExample {
    public static void main(String[] args) {
        int number = 13;
        if (number % 2 == 0) {
            System.out.println("这是一个偶数");
        } else {
            System.out.println("这是一个奇数");
        }
    }
}

嵌套if语句

if-else-if多选择语句

public class IfElseIfExample {
    public static void main(String[] args) {
        int marks = 65;

        if (marks < 50) {
            System.out.println("fail");
        } else if (marks >= 50 && marks < 60) {
            System.out.println("D grade");
        } else if (marks >= 60 && marks < 70) {
            System.out.println("C grade");
        } else if (marks >= 70 && marks < 80) {
            System.out.println("B grade");
        } else if (marks >= 80 && marks < 90) {
            System.out.println("A grade");
        } else if (marks >= 90 && marks < 100) {
            System.out.println("A+ grade");
        } else {
            System.out.println("Invalid!");
        }
    }
}                    // C gradee


switch多选择结构

public class SwitchExample {
    public static void main(String[] args) {
        int number = 20;
        switch (number) {
        case 10:
            System.out.println("10");
            break;
        case 20:
            System.out.println("20");
            break;
        case 30:
            System.out.println("30");
            break;
        default:
            System.out.println("Not in 10, 20 or 30");
        }
    }
}                //20

注意有没有break的情况!


循环结构

for循环(适合确定循环次数时使用)

简单for循环

/*
 * for循环语句的格式
 *      for(初始化语句; 判断条件语句; 控制条件语句;) {
 *          循环体语句;
 *      }
 * 
 *  执行流程:
 *      A:执行初始化语句
 *      B:执行判断条件语句,看其结果是true还是false
 *          如果是false,就结束循环
 *          如果是true,就继续执行
 *      C:执行循环体语句
 *      D:执行控制条件语句
 *      E:回到B继续
 * 
 */
public class ForDemo02 {
    public static void main(String[] args) {
        //计算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("0到100之间所有奇数的和为"+oddSum);
        System.out.println("0到100之间所有偶数的和为"+evenSum);

    }
}

for-each

for-each循环用于在java中遍历数组或集合。

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

        //遍历数组的元素
        for(int x:numbers){
            System.out.println(x);
        }
     }
 }

标记for循环

public class LabeledForExample {
    public static void main(String[] args) {
        aa: for (int i = 1; i <= 3; i++) {
            bb: for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break bb;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}

执行上面的代码,得到如下结果 :
1 1
1 2
1 3
2 1
3 1
3 2
3 3


实现绘制九九乘法表

在这里插入图片描述

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

while循环(适合不确定循环次数时使用)

public class WhileDemo02 {
    public static void main(String[] args) {
        //计算1、2、3...到100的和
        int i = 0;
        int sum = 0;
        while (i<=100){
            sum =sum +i;
            i++;
        }
        System.out.println(sum);
    }
}

do-while循环(适合不确定循环次数时使用)

do-while循环至少执行一次,因为它是在循环体之后检查条件。

public class DoWhileDemo01 {
    public static void main(String[] args) {
        //计算1-100的和
        int i = 0;
        int sum = 0;
        do {
                sum =sum +i;
                i++;
        } while (i<=100);
        System.out.println(sum);
    }
}

breake :用于强行退出循环

public class BreakExample2 {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}

结果如下: 1 1
1 2
1 3
2 1
3 1
3 2
3 3


continue:用于退出某次循环过程

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                continue;
            }
            System.out.println(i);
        }
    }
}

1
2
3
4
6
7
8
9

无限循环

无限循环的表示方式:

for( ; ; )——即去掉判断条件

while(true)

while()是一个循环,直到条件不满足,才退出while代码块的范围;
if()只执行一次,成立进入,运行完后直接执行if之后的代码,不会再进入if代码的范围;

Scanner对象

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

基本语法:

 Scanner scanner = new Scanner(System.in);

Scanner类的next() 与nextLine() 方法获取输入的字符串
hasNext() 与hasNetLine() 判断是否还有输入的数据

next()

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

nextLine()

  • 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
  • 可以获得空白
//创建一个扫描对象,用于接受键盘上的数据
Scanner scanner = new Scanner(System.in);
System.out.println("采用nextLine方式接收数据,");
//判断用户有没有输入字符串
if (scanner.hasNextLine()) {
    //使用nextLine方式接收
    String str = scanner.nextLine();
    System.out.println("输入的内容为:" + str);
}

System.out.println("采用nextFloat方式接收数据,");
//判断用户有没有输入浮点数
while (scanner.hasNextFloat()) {
    float str2 = scanner.nextFloat();
    System.out.println(str2);
}

//凡是属于IO流的类,如果不关闭会一直占用资源,要养成好习惯用完关掉
scanner.close();

使用nextInt()方法读取整数,使用nextFloat()方法读取单精度浮点数

import java.util.Scanner;

public class ScannerTest {

        public static void main(String[] args) {
            //输入多个数字,并求其总和和平均数,每输入一个数字用回车确认,
            //通过输入非数字来结束输入并输出执行结果

            Scanner scanner = new Scanner(System.in);

            //和
            double sum = 0;
            // 统计输入数字个数
            int total = 0;

            System.out.println("请输入需要计算的数据:");

            //通过循环判断是否还有输入,并在里面对每一次进行求和和统计
            while (scanner.hasNextDouble()) {
                double x = scanner.nextDouble();
                total++;
                sum += x;
                System.out.println("输入了第" + total + "个数据,当前结果为sum=" + sum);
            }

            System.out.println(total + "个数的和为" + sum + ";平均数为" + (sum / total));
            
            scanner.close();
        }

}

image.png

数组

同一种类型数据的集合。其实数组是一个容器。数组下标从0开始。
数组的长度一旦声明,不可变

格式一
元素类型[] 数组名 = new 元素类型[元素个数或者数组长度]

int[] a = new int[5];

格式二
元素类型[] 数组名 = new 元素类型[]{元素,元素,......}

int[] b = new int[]{10,12,3,4};
int[] c = {6,2,5};

遍历: 通过数组名.length获取数组长度;

for (int index = 0; index < a.length; index++) {
    System.out.print(a[index]+"\t");
}

常见异常:
java.lang.ArrayIndexOutOfBoundsException 数组下标越界

public static void main(String[] args) {
    int[] a = new int[3];
    int[] b = new int[]{10,12,3,40,20,32,1,99,52};
    int[] c = {6,2,5};
    a[0] = 10;
    a[1] = 1;
    a[2] = 3;

    System.out.println(b[0]);
    System.out.println(c[1]);
    System.out.println("数组a的长度是:"+a.length);

    //数组求最大数
    int max = 0;
    for (int i = 0; i < b.length; i++) {
        if (i == 0){
            max =b[i];
            continue;
        }
        if (b[i] >max){
            max = b[i];
        }
    }
    System.out.println("数组b当中的最大值是"+max);

    //遍历输出数组b
    for (int index = 0; index < b.length; index++) {
        System.out.print(b[index]+"\t");
    }
    System.out.println("实现翻转数组:");

    //实现翻转数组,首位互换位置
    int temp =0;
    for (int i = 0; i < b.length/2; i++) {
        temp = b[b.length-1-i];
        b[b.length-1-i] = b[i];
        b[i] = temp;
    }
    for (int j : b) {
        System.out.print(j + "\t");
    }
    System.out.println();

    //使用java 8 Stream API
    System.out.println(Arrays.toString(IntStream.rangeClosed(1, b.length)
            .mapToObj(i -> b[b.length - i])
            .toArray()));

    //使用Collections.reverse()方法
    List<Object> list = Arrays.asList(b);
    Collections.reverse(list);
    for (int j : b) {
        System.out.print(j + "\t");
    }

}
 public static void main(String[] args) {
        test01();

        int[] arr2 = new int[]{10,20,30,40};
        int inputNum = 20;
        System.out.println(test02(arr2,inputNum));


    }

    /**
    * @Description:  将两个新的数组合并生成一个新的数组
    * @Param:
    * @return:
    * @Author: BiMoYuanKong
    * @Date: 2022/5/6
    */
    // 思路:
    // 1、声明一个新的数组长度为两个数组长度的和
    // 2、将第一个数组循环赋值给新数组
    // 3、讲第二个数组循环赋值给新数组 注意:第二个数组赋值时的起始位置
    public static void test01(){
        int[] arr0 = { 0, 10, 4, 84, 8 };
        int[] arr1 = { 2, 3, 5, 88, 9 };
        int[] arr2 = new int [arr0.length+arr1.length];
        for (int i = 0; i <arr0.length ; i++) {
            int num = arr0[i];
            arr2[i] = num;
        }

        for (int i = 0; i <arr1.length ; i++) {
            int num = arr1[i];
            arr2[arr0.length+i] = num;
        }
//        System.arraycopy(arr1, 0, arr2, arr0.length + 0, arr1.length);
        System.out.println(Arrays.toString(arr2));
    }

    //如何检测一个数组中是否包含某一个数据
    public static boolean test02(int[] arr2,int inputNum){
        for (int s : arr2) {
            if (s == inputNum)
                return true;
        }
        return false;
    }