花几千上万学习Java,真没必要!(十一)

1、跳转控制语句:

测试代码1:

package com.continuetest;
public class ControlFlowDemo {  
  
    // break语句  
    public void demonstrateBreak() {  
        for (int i = 0; i < 10; i++) {  
            if (i == 5) {  
                break; // 当i等于5时,跳出循环  
            }  
            System.out.println("在break之前的循环: " + i);  
        }  
        System.out.println("跳出循环后");  
    }  
  
    // continue语句  
    public void demonstrateContinue() {  
        for (int i = 0; i < 10; i++) {  
            if (i % 2 == 0) {  
                continue; // 跳过偶数  
            }  
            System.out.println("循环中的奇数: " + i);  
        }  
    }  
  
    // return语句  
    public int findMax(int[] numbers) {  
        int max = numbers[0];  
        for (int number : numbers) {  
            if (number > max) {  
                max = number;  
            }  
        }  
        return max; // 返回最大值  
    }  
  
    // 异常处理  
    public void testException() {  
        try {  
            // 假设这里有一段可能抛出异常的代码  
            int result = 10 / 0; // 这会抛出ArithmeticException  
        } catch (ArithmeticException e) {  
            System.out.println("除数不能为0");  
        }  
        // 无论是否发生异常,这里的代码都会执行  
        System.out.println("异常处理后的继续执行");  
    }  
  
    // 主方法,用于测试上述方法  
    public static void main(String[] args) {  
        ControlFlowDemo demo = new ControlFlowDemo();  
  
        demo.demonstrateBreak();  
        System.out.println("--------");  
  
        demo.demonstrateContinue();  
        System.out.println("--------");  
  
        int[] numbers = {3, 5, 1, 8, 2, 9};  
        System.out.println("数组中的最大值是: " + demo.findMax(numbers));  
        System.out.println("--------");  
  
        demo.testException();  
    }  
}

运行结果如下:

测试代码2: 

package com.continuetest;
//跳转语句
public class JumpControlStatementsExample {  
    public static void main(String[] args) {  
        // break语句  
        System.out.println("break语句:");  
        forLoopWithBreak();  
  
        // continue语句  
        System.out.println("\ncontinue语句:");  
        forLoopWithContinue();  
  
        // return语句(从方法中返回)  
        System.out.println("\nreturn语句(从方法中返回):");  
        int max = getMax(5, 10);  
        System.out.println("较大的数是: " + max);  
  
        // void方法中的return语句  
        System.out.println("\nvoid方法中的return语句:");  
        printMessage();  
    }  
  
    // break语句的方法  
    public static void forLoopWithBreak() {  
        for (int i = 0; i < 10; i++) {  
            if (i == 5) {  
                break; // 当i等于5时,跳出循环  
            }  
            System.out.println(i);  
        }  
    }  
  
    // continue语句的方法  
    public static void forLoopWithContinue() {  
        for (int i = 0; i < 10; i++) {  
            if (i % 2 == 0) {  
                continue; // 如果i是偶数,跳过当前循环的剩余部分  
            }  
            System.out.println(i); // 只打印奇数  
        }  
    }  
  
    // return语句(从方法中返回)的方法  
    public static int getMax(int a, int b) {  
        if (a > b) {  
            return a; // 返回较大的数  
        }  
        return b; // 返回较小的数(如果a不大于b)  
    }  
  
    // void方法中的return语句的方法  
    public static void printMessage() {  
        System.out.println("Hello, World!");  
        return; // 终止方法,但不需要返回值  
    }  
}

运行结果如下:

 

 

 

2、 嵌套循环:

测试代码1: 

package com.continuetest;
//循环嵌套
public class ComplexNestedLoopsExample {  
    public static void main(String[] args) {  
        // 初始化一个二维整数数组  
        int[][] matrix = {  
            {1, 2, 3, 4},  
            {5, 6, 7, 8},  
            {9, 10, 11, 12},  
            {13, 14, 15, 16}  
        };  
          
        // 遍历二维数组的行  
        for (int i = 0; i < matrix.length; i++) {  
            // 对于每一行,检查是否满足某个条件(例如:行号是否为偶数)  
            if (i % 2 == 0) {  
                // 如果行号为偶数,遍历该行的列  
                for (int j = 0; j < matrix[i].length; j++) {  
                    // 对每个元素,执行一些操作  
                    // 假设要检查元素是否大于其行索引的两倍  
                    if (matrix[i][j] > (i * 2)) {  
                        // 如果条件满足,打印该元素,并可能想对其执行更多操作  
                        System.out.println("元素 " + matrix[i][j] + " 满足条件(在偶数行中)");  
                          
                        // 假设还要根据元素的奇偶性决定是否重复某些操作  
                        int k = 0;  
                        while (k < (matrix[i][j] % 2 == 0 ? 2 : 1)) { // 如果是偶数,则重复两次;否则,一次  
                            System.out.println("对元素 " + matrix[i][j] + " 重复操作 " + (k + 1));  
                            k++;  
                        }  
                    }  
                }  
            } else {  
                // 如果行号不是偶数,可能会执行不同的操作或跳过  
                // 使用do...while循环演示即使条件不满足也会至少执行一次的情况  
                int firstElement = (matrix[i].length > 0) ? matrix[i][0] : -1; // 安全地获取第一个元素  
                do {  
                    System.out.println("在奇数行中,但仅对第一个元素 " + firstElement + " 执行操作");  
                } while (false); // 这里条件总是为false,所以do...while循环只执行一次  
            }  
        }  
    }  
}

运行结果如下:

 

测试代码2:

package com.continuetest;
//嵌套循环
public class NestedStructuresExample {  
    public static void main(String[] args) {  
        // 初始化一个整数数组  
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
          
        // 初始化一个计数器,并统计偶数的数量  
        int evenCount = 0;  
          
        // 顺序结构:先进行循环遍历  
        for (int i = 0; i < numbers.length; i++) { // 循环结构  
            // 顺序结构:在循环体内,先访问数组元素  
            int number = numbers[i];  
              
            // 分支结构:判断当前元素是否为偶数  
            if (number % 2 == 0) { 
                // 顺序结构:如果是偶数,则执行打印操作  
                System.out.println(number + " 是偶数");  
                  
                // 顺序结构:同时,更新偶数的计数器  
                evenCount++;  
            }  
        }  
          
        // 顺序结构:循环结束后,打印偶数的总数  
        System.out.println("数组中共有 " + evenCount + " 个偶数。");  
    }  
}

运行结果如下:

测试代码3:

package com.continuetest;
//嵌套循环
public class NestedStructuresTest {  
    public static void main(String[] args) {  
        // 初始化一个整数数组  
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
          
        // 使用for循环遍历数组  
        for (int i = 0; i < numbers.length; i++) {  
            
            // 添加一个while循环
            int j = 0;  
            while (j < 5) { // 假设只对每个元素执行5次操作  
                if (numbers[i] % 2 == 0) {  
                    System.out.println(numbers[i] + " 是偶数(由while循环处理)");  
                }  
                j++;  
            }  
              
            // 添加一个do...while循环
            // do...while至少会执行一次循环体  
            int k = 0;  
            do {  
                if (numbers[i] > 5) {  
                    System.out.println(numbers[i] + " 大于5(由do...while循环处理)");  
                }  
                k++;  
            } while (k < 1); // 限制为只执行一次
        }  
          
 
        // 添加一个单独的计数器来统计偶数  
        int evenCount = 0;  
        for (int num : numbers) { // 使用for循环遍历  
            if (num % 2 == 0) {  
                evenCount++;  
            }  
        }  
          
        // 打印偶数的总数  
        System.out.println("数组中共有 " + evenCount + " 个偶数。");  
    }  
}

运行结果如下:

 

测试代码4:

package com.continuetest;
import java.util.function.Predicate;
//用嵌套循环处理字符串
public class StringProcessor {  
	  
    // 翻转字符串
    public String reverseString(String str) {  
        StringBuilder sb = new StringBuilder();  
        for (int i = str.length() - 1; i >= 0; i--) {  
            sb.append(str.charAt(i));  
        }  
        return sb.toString();  
    }  
  
    // 查找并替换子字符串(  
    public String replaceSubstring(String str, String toFind, String replaceWith) {  
        StringBuilder sb = new StringBuilder(str);  
        int index = 0;  
        while ((index = sb.indexOf(toFind, index)) != -1) {  
            sb.replace(index, index + toFind.length(), replaceWith);  
            index += replaceWith.length(); // 更新索引以避免跳过字符  
        }  
        return sb.toString();  
    }  
  
    // 字符串分割与重组 
    public String filterAndRecombine(String str, String delimiter, Predicate<String> filter) {  
        String[] parts = str.split(delimiter);  
        StringBuilder sb = new StringBuilder();  
        for (String part : parts) {  
            if (filter.test(part)) {  
                sb.append(part).append(delimiter); 
            }  
        }  
        // 移除尾随的分隔符( 
        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == delimiter.charAt(0)) {  
            sb.setLength(sb.length() - 1);  
        }  
        return sb.toString();  
    }  
  
  
    // 字符统计,只统计ASCII字符
    public int[] countCharacters(String str) {  
        int[] count = new int[256]; // 只处理ASCII字符  
        for (int i = 0; i < str.length(); i++) {  
            char c = str.charAt(i);  
            count[c]++;  
        }  
        return count;  
    }  
    
    // 主方法(用于测试)  
    public static void main(String[] args) {  
        StringProcessor processor = new StringProcessor();  
  
        String original = "Hello, World!mfdka;gjeklhmtahterhbt;="
        		+ "]"
        		+ " tyerytue56dsafw3ghtr278";  
        String reversed = processor.reverseString(original);  
        System.out.println("Reversed: " + reversed);  
  
        String toReplace = "World";  
        String withWhat = "Java";  
        String replaced = processor.replaceSubstring(original, toReplace, withWhat);  
        System.out.println("Replaced: " + replaced);  
  
        String commaSeparated = "apple,banana,cherry,date";  
        String filtered = processor.filterAndRecombine(commaSeparated, ",", part -> part.startsWith("a"));  
        System.out.println("Filtered and Recombined: " + filtered);  
  
        int[] charCounts = processor.countCharacters(original);  
        // 打印字符统计数组的长度
        System.out.println("Character counts array length: " + charCounts.length);  
    }  
}  

运行结果如下:

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值