Java 程序:continue
语句
原文:https://www.studytonight.com/java-programs/java-continue-statement-programs
在本教程中,我们将学习如何在不同的场景中使用 continue 语句。但是在继续之前,如果你不熟悉 break 语句的概念,那么一定要查看 Java 中 Continue 语句的文章。
语法:
jump-statement;
continue;
程序 1: Java continue
语句程序
在这个程序中,我们将在 for 循环中看到 continue 语句的实现。
算法:
- 开始
- 使用 for 循环打印从 1 到 10 的元素。
- 如果遇到 6,则跳过该元素。
- 打印剩余的元素。
- 停下来。
下面是相同的代码。
//Java Program to see the implementation of continue statement
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
System.out.println("The elements are: ");
for(int i=1;i<=10;i++)
{
if(i==6)
{
continue;
}
System.out.println(i);
}
}
}
元素为: 1 2 3 4 5 7 8 9 10
程序 2: Java continue
语句程序
在这个程序中,我们将在一个内部循环中看到 continue 语句的实现。
算法:
- 开始
- 循环使用两个。
- 从 1 到 3 运行两个循环。
- 如果 for 循环的索引都匹配,则使用 continue 语句。
- 打印元素。
- 停下来。
下面是相同的代码。
//Java Program to see the implementation of continue statement
public class Main
{
public static void main(String[] args)
{
//outer loop
for(int i=1;i<=3;i++)
{
//inner loop
for(int j=1;j<=3;j++)
{
if(i==j)
{
//using continue statement inside inner loop
continue;
}
//Print the elements
System.out.println(i+" "+j);
}
}
}
}
1 2 1 3 2 1 2 3 3 1 3 2
程序 3: Java continue
语句程序
在这个程序中,我们将在 do-while 循环中看到 continue 语句的实现。
算法:
- 开始
- 使用边做边循环打印小于 10 的元素。
- 从 0 到 10 运行循环。
- 如果元素是 5,则使用 continue 语句。
- 打印元素。
- 在每次迭代中增加循环变量的值。
- 停下来。
下面是相同的代码。
//Java Program to see the implementation of continue statement
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int j=0;
do
{
if (j==5)
{
j++;
continue;
}
System.out.print(j+ " ");
j++;
}while(j<10);
}
}
0 1 2 3 4 6 7 8 9
程序 4: Java continue
语句程序
在这个程序中,我们将看到如何打印所有正输入数字的总和。
算法:
- 开始
- 为数字和总和声明变量。
- 将总和初始化为 0。
- 创建 Scanner 类的实例。
- 使用 for 循环输入数字。
- 检查数字是否为正数。
- 如果输入了任何负数,请使用 continue 语句。
- 在每次迭代中增加总和。
- 显示总和。
- 停下来。
下面是相同的代码。
//Java Program to implement the continue statement
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int num, sum = 0;
// create an object of Scanner
Scanner sc = new Scanner(System.in);
for (int i = 1; i < 10; ++i)
{
System.out.println("Enter number " + i + " : ");
// takes input from the user
num = sc.nextInt();
// if number is negative
// continue statement is executed
if (num <= 0) {
continue;
}
sum += num;
}
System.out.println("The sum of all the numbers = " + sum);
sc.close();
}
}
输入 1: 7 输入 2: 6 输入 3: 5 输入 4: 4 输入 5: 8 输入 6: -9 输入 7: 1 输入 8: 2 输入 9 : 3 所有数字之和= 36