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

时间:2016-09-18 16:21:59

标签: java

这是我的代码

    var objectToSave: PFObject?

    let query = PFQuery(className: "Collabs")
    query.getObjectInBackground(withId: collabID) { (object, error) in
        if error != nil {
            print(error)
        } else {
            if let content = object {
                objectToSave = content
            }
            if objectToSave != nil {

                objectToSave!["testArray"] = ["foo","bar","foobar"]

                objectToSave!.saveInBackground(block: { (success, error) in
                    if error != nil {
                        print("ERROR")
                    } else {
                        print("SUCCESS")
                    }
                })
            }
        }
    }

我想更改此代码,以便循环结束而不必使用student = 10来结束循环。我想不出任何会结束循环的事情。并将其转换为while循环到目前为止我有

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);

    }
}

但我不知道如果输入0,如何结束循环我们不允许使用break;退出循环可以得到一些帮助吗?

3 个答案:

答案 0 :(得分:1)

结束循环的方法是:

  • 使用break
  • 如果在下一次交互中不满足条件
  • 在方法中包含循环并使用return

答案 1 :(得分:0)

使用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);
}

答案 2 :(得分:0)

这个怎么样:

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);