简体   繁体   English

不使用 break 结束循环并将 for 循环转换为 while

[英]ending loop without use of break and convert for loop to while

this is my code这是我的代码

import java.util.*;
public class test3
{
    public static void main (String [] args)
    {
        int sum = 0;
        int mark;
        Scanner sc = new Scanner(System.in);
        for (int student = 1; student <=10; student++)
        {
            System.out.println("enter mark");
            mark = sc.nextInt();
            if (mark > 0)
            {
                sum = sum + mark;
            }
            else
            {
                student = 10;
            }
        }
        System.out.println("sum is" + sum);

    }
}

i want to change this code so that the loop ends without having to use student = 10 to end loop.我想更改此代码,以便循环结束而不必使用 student = 10 来结束循环。 i cant think of anything that would end the loop.我想不出任何可以结束循环的东西。 and also convert it to a while loop so far i have并将其转换为 while 循环到目前为止我有

int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);

    while (student <= 10)
    {
        System.out.println("enter mark");
        mark = sc.nextInt();
        sum = sum  + mark;
        student++;
    }

but i dont know how to end loop if 0 is input we're not allowed to use break;但如果输入 0,我不知道如何结束循环,我们不允许使用 break; to exit loop could i get some help please?退出循环我能得到一些帮助吗?

The ways for ending loops are:结束循环的方法是:

  • using break使用break
  • if the condition is not satisfied in the next interation如果在下一次交互中不满足条件
  • Including the loop in a method and using return在方法中包含循环并使用return

Use while (student <= 10) condition and student = 10 statement to exit the loop:使用while (student <= 10)条件和student = 10语句退出循环:

public static void main(String[] args) {
    int sum = 0;
    int mark;
    Scanner sc = new Scanner(System.in);
    int student = 1;
    while (student <= 10) {
        System.out.println("enter mark");
        mark = sc.nextInt();
        if (mark > 0) {
            sum = sum + mark;
        } else {
            student = 10;
        }
        student++;
    }
    System.out.println("sum is" + sum);
}

What about this:那这个呢:

int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);

while (student <= 10) {
    System.out.println("enter mark: ");
    mark = sc.nextInt();
    if (mark > 0) {
        sum += mark;
    } else {
        student = 10;
    }
    student++;
}
System.out.println("sum is = " + sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM