continue 关键字
概述
continue
关键字用于跳过当前循环迭代中continue语句之后的代码,直接进入下一次循环迭代。
语法格式
// 简单continue
continue;
// 带标签的continue
continue label;
基本用法
public class ContinueExample {
public static void main(String[] args) {
// 在for循环中使用continue
System.out.println("=== for循环中的continue ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
System.out.println("奇数: " + i);
}
// 在while循环中使用continue
System.out.println("\n=== while循环中的continue ===");
int count = 0;
while (count < 10) {
count++;
if (count % 3 == 0) {
continue; // 跳过3的倍数
}
System.out.println("不是3的倍数: " + count);
}
// 在do-while循环中使用continue
System.out.println("\n=== do-while循环中的continue ===");
int num = 0;
do {
num++;
if (num == 5) {
continue; // 跳过数字5
}
System.out.println("数字: " + num);
} while (num < 8);
}
}
数组和集合处理
import java.util.*;
public class ContinueArrayProcessing {
// 过滤数组元素
public static void filterArray() {
int[] numbers = {1, -2, 3, 0, -5, 6, 7, -8, 9, 0};
int positiveSum = 0;
int processedCount = 0;
System.out.println("处理数组,只累加正数:");
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
System.out.println("跳过非正数: " + numbers[i]);
continue; // 跳过负数和零
}
positiveSum += numbers[i];
processedCount++;
System.out.println("处理正数: " + numbers[i] + ",当前累计: " + positiveSum);
}
System.out.println("正数总和: " + positiveSum + ",处理了 " + processedCount + " 个正数");
}
// 处理字符串列表
public static void processStringList() {
List<String> words = Arrays.asList("hello", "", "world", null, "java", " ", "programming");
List<String> validWords = new ArrayList<>();
System.out.println("处理字符串列表,过滤无效字符串:");
for (String word : words) {
if (word == null) {
System.out.println("跳过null值");
continue; // 跳过null
}
if (word.trim().isEmpty()) {
System.out.println("跳过空字符串: '" + word + "'");
continue; // 跳过空字符串
}
validWords.add(word.trim());
System.out.println("添加有效字符串: " + word.trim());
}
System.out.println("有效字符串: " + validWords);
}
// 矩阵处理
public static void processMatrix() {
int[][] matrix = {
{1, 0, 3},
{4, 5, 0},
{0, 8, 9}
};
System.out.println("处理矩阵,跳过零值:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
System.out.println("跳过零值在位置 [" + i + "][" + j + "]");
continue; // 跳过零值
}
// 处理非零值
matrix[i][j] = matrix[i][j] * 2;
System.out.println("处理位置 [" + i + "][" + j + "], 值: " + matrix[i][j]);
}
}
System.out.println("处理后的矩阵:");
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
public static void main(String[] args) {
filterArray();
System.out.println();
processStringList();
System.out.println();
processMatrix();
}
}
带标签的continue
public class LabeledContinueExample {
public static void basicLabeledContinue() {
System.out.println("=== 基本带标签的continue ===");
outer: for (int i = 1; i <= 3; i++) {
inner: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("跳过外层循环的当前迭代");
continue outer; // 跳过外层循环的当前迭代
}
System.out.println("i=" + i + ", j=" + j);
}
System.out.println("外层循环 " + i + " 完成");
}
}
public static void complexLabeledContinue() {
System.out.println("\n=== 复杂的带标签continue ===");
int[][] grid = {
{1, 2, 3, 4},
{5, 0, 7, 8},
{9, 10, 11, 12}
};
rowLoop: for (int row = 0; row < grid.length; row++) {
System.out.println("处理第 " + (row + 1) + " 行:");
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == 0) {
System.out.println(" 发现零值,跳过整行");
continue rowLoop; // 跳过整行
}
if (grid[row][col] % 2 == 0) {
System.out.println(" 跳过偶数: " + grid[row][col]);
continue; // 只跳过当前元素
}
System.out.println(" 处理奇数: " + grid[row][col]);
}
System.out.println(" 第 " + (row + 1) + " 行处理完成");
}
}
public static void searchExample() {
System.out.println("\n=== 搜索示例 ===");
String[] categories = {"电子产品", "图书", "服装", "食品"};
String[][] products = {
{"手机", "电脑", "耳机"},
{"小说", "教材", "杂志"},
{"衬衫", "裤子", "鞋子"},
{"苹果", "面包", "牛奶"}
};
String target = "教材";
boolean found = false;
searchLoop: for (int i = 0; i < categories.length; i++) {
System.out.println("搜索类别: " + categories[i]);
for (int j = 0; j < products[i].length; j++) {
if (products[i][j].equals(target)) {
System.out.println("找到目标产品: " + target + " 在类别 " + categories[i]);
found = true;
continue searchLoop; // 找到后继续搜索其他类别
}
System.out.println(" 检查产品: " + products[i][j]);
}
}
if (!found) {
System.out.println("未找到目标产品: " + target);
}
}
public static void main(String[] args) {
basicLabeledContinue();
complexLabeledContinue();
searchExample();
}
}
实际应用场景
import java.util.*;
import java.io.*;
public class ContinueApplications {
// 日志文件处理
public static void processLogFile() {
System.out.println("=== 日志文件处理 ===");
String[] logLines = {
"2023-12-01 10:00:00 INFO 用户登录成功",
"2023-12-01 10:01:00 DEBUG 调试信息",
"2023-12-01 10:02:00 ERROR 数据库连接失败",
"",
"2023-12-01 10:03:00 WARN 内存使用率过高",
"# 这是注释行",
"2023-12-01 10:04:00 INFO 用户退出",
"2023-12-01 10:05:00 ERROR 文件读取失败"
};
int errorCount = 0;
int processedLines = 0;
for (String line : logLines) {
// 跳过空行
if (line.trim().isEmpty()) {
continue;
}
// 跳过注释行
if (line.startsWith("#")) {
continue;
}
// 跳过DEBUG级别的日志
if (line.contains("DEBUG")) {
continue;
}
processedLines++;
if (line.contains("ERROR")) {
errorCount++;
System.out.println("错误日志: " + line);
} else {
System.out.println("正常日志: " + line);
}
}
System.out.println("处理了 " + processedLines + " 行日志,发现 " + errorCount + " 个错误");
}
// 数据验证和清理
public static void validateData() {
System.out.println("\n=== 数据验证和清理 ===");
Map<String, Object> userData = new HashMap<>();
userData.put("name", "张三");
userData.put("age", 25);
userData.put("email", "zhangsan@example.com");
userData.put("phone", "");
userData.put("address", null);
userData.put("salary", -1000);
userData.put("department", "IT");
Map<String, Object> cleanData = new HashMap<>();
for (Map.Entry<String, Object> entry : userData.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// 跳过null值
if (value == null) {
System.out.println("跳过null值字段: " + key);
continue;
}
// 跳过空字符串
if (value instanceof String && ((String) value).trim().isEmpty()) {
System.out.println("跳过空字符串字段: " + key);
continue;
}
// 跳过负数(对于数值字段)
if (value instanceof Number && ((Number) value).doubleValue() < 0) {
System.out.println("跳过负数字段: " + key + " = " + value);
continue;
}
cleanData.put(key, value);
System.out.println("保留有效字段: " + key + " = " + value);
}
System.out.println("清理后的数据: " + cleanData);
}
// 批量文件处理
public static void processBatchFiles() {
System.out.println("\n=== 批量文件处理 ===");
String[] filenames = {
"document.txt",
"backup.bak",
"image.jpg",
"script.sh",
"data.csv",
"temp.tmp",
"config.xml"
};
String[] validExtensions = {".txt", ".csv", ".xml"};
List<String> processedFiles = new ArrayList<>();
for (String filename : filenames) {
// 跳过备份文件
if (filename.endsWith(".bak") || filename.endsWith(".tmp")) {
System.out.println("跳过临时/备份文件: " + filename);
continue;
}
// 检查文件扩展名
boolean validExtension = false;
for (String ext : validExtensions) {
if (filename.toLowerCase().endsWith(ext)) {
validExtension = true;
break;
}
}
if (!validExtension) {
System.out.println("跳过不支持的文件类型: " + filename);
continue;
}
// 模拟文件处理
System.out.println("处理文件: " + filename);
processedFiles.add(filename);
}
System.out.println("成功处理的文件: " + processedFiles);
}
public static void main(String[] args) {
processLogFile();
validateData();
processBatchFiles();
}
}
性能优化应用
import java.util.*;
public class ContinuePerformanceOptimization {
// 大数据集过滤
public static void optimizedFiltering() {
System.out.println("=== 大数据集过滤优化 ===");
List<Integer> largeDataset = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
largeDataset.add(i);
}
List<Integer> primes = new ArrayList<>();
long startTime = System.currentTimeMillis();
for (int number : largeDataset) {
// 跳过偶数(除了2)
if (number > 2 && number % 2 == 0) {
continue;
}
// 检查是否为质数
if (isPrime(number)) {
primes.add(number);
}
}
long endTime = System.currentTimeMillis();
System.out.println("找到 " + primes.size() + " 个质数");
System.out.println("处理时间: " + (endTime - startTime) + "ms");
System.out.println("前10个质数: " + primes.subList(0, Math.min(10, primes.size())));
}
private static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
// 条件跳过优化
public static void conditionalSkipping() {
System.out.println("\n=== 条件跳过优化 ===");
int[][] matrix = new int[100][100];
// 填充矩阵
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
matrix[i][j] = i * 100 + j;
}
}
long sum = 0;
int processedElements = 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < matrix.length; i++) {
// 跳过偶数行
if (i % 2 == 0) {
continue;
}
for (int j = 0; j < matrix[i].length; j++) {
// 跳过偶数列
if (j % 2 == 0) {
continue;
}
// 跳过对角线元素
if (i == j) {
continue;
}
sum += matrix[i][j];
processedElements++;
}
}
long endTime = System.currentTimeMillis();
System.out.println("处理了 " + processedElements + " 个元素");
System.out.println("总和: " + sum);
System.out.println("处理时间: " + (endTime - startTime) + "ms");
}
public static void main(String[] args) {
optimizedFiltering();
conditionalSkipping();
}
}
最佳实践
public class ContinueBestPractices {
// 1. 清晰的跳过条件
public static void clearSkipConditions() {
int[] scores = {85, -1, 92, 0, 78, 95, -1, 88};
double totalScore = 0;
int validCount = 0;
for (int score : scores) {
// 清晰的跳过条件:无效分数
if (score < 0 || score > 100) {
System.out.println("跳过无效分数: " + score);
continue;
}
totalScore += score;
validCount++;
}
if (validCount > 0) {
double average = totalScore / validCount;
System.out.println("平均分: " + String.format("%.2f", average));
}
}
// 2. 避免过度嵌套
public static void avoidDeepNesting() {
List<String> userInputs = Arrays.asList("", "valid", null, " ", "another", "123", "test");
List<String> processedInputs = new ArrayList<>();
for (String input : userInputs) {
// 使用continue避免深层嵌套
if (input == null) {
continue; // 跳过null
}
if (input.trim().isEmpty()) {
continue; // 跳过空字符串
}
if (input.matches("\\d+")) {
continue; // 跳过纯数字
}
// 处理有效输入
processedInputs.add(input.trim().toLowerCase());
}
System.out.println("处理后的输入: " + processedInputs);
}
// 3. 合理使用标签
public static void reasonableLabelUsage() {
int[][] data = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
processingLoop: for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (data[i][j] == 0) {
System.out.println("发现零值在 [" + i + "][" + j + "],跳过当前行");
continue processingLoop; // 合理使用标签
}
System.out.println("处理元素: " + data[i][j]);
}
}
}
// 4. 性能考虑
public static void performanceConsiderations() {
List<String> largeList = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
largeList.add("item" + i);
}
// 高效的过滤
List<String> filtered = new ArrayList<>();
for (String item : largeList) {
// 快速跳过条件放在前面
if (item.length() < 5) {
continue;
}
if (!item.contains("5")) {
continue;
}
// 复杂处理只对符合条件的项进行
filtered.add(item.toUpperCase());
}
System.out.println("过滤后的项目数量: " + filtered.size());
}
public static void main(String[] args) {
System.out.println("=== 清晰的跳过条件 ===");
clearSkipConditions();
System.out.println("\n=== 避免过度嵌套 ===");
avoidDeepNesting();
System.out.println("\n=== 合理使用标签 ===");
reasonableLabelUsage();
System.out.println("\n=== 性能考虑 ===");
performanceConsiderations();
}
}
continue关键字是控制循环流程的重要工具,能够让代码更简洁、逻辑更清晰,特别适用于过滤和条件跳过场景。