Java 如何从嵌套的for循环中断到其最外层的循环?

Java 如何从嵌套的for循环中断到其最外层的循环?,java,Java,我试图解决一个问题,在这个问题中,我必须找到3个数字,这些数字加起来等于t个案例的n个数字 这里是限制 Given four numbers N,A,B,C, find three numbers that sum up to N, with the following restrictions: The first number must be an integer between 0 and A (inclusive) The second number must be an intege

我试图解决一个问题,在这个问题中,我必须找到3个数字,这些数字加起来等于t个案例的n个数字

这里是限制

Given four numbers N,A,B,C, find three numbers that sum up to N, with the following restrictions:

The first number must be an integer between 0 and A (inclusive)
The second number must be an integer between 0 and B (inclusive)
The third number must be an integer between 0 and C (inclusive)
我目前有一个有效的解决方案,但是我的解决方案打印出了每一个可能的答案,而不是第一个正确答案。一旦找到第一个解决方案,我如何能够返回到我的第一个for循环

以下是问题的链接:

这是我的密码:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        int t = input.nextInt();

        for(int i=0;i<t;i++){

            int n = input.nextInt();
            int a = input.nextInt();
            int b = input.nextInt();
            int c = input.nextInt();

            if(n<0){
                System.out.println("-1");
            }
            else{
                for(int one=0; one<(a+1); one++){
                    for(int two=0; two<(b+1); two++){
                        for(int three=0; three<(c+1); three++){
                            if((one+two+three)==n){
                                System.out.println(one+" "+two+" "+three);
                                break;
                            }
                        }
                    }
                }

            }
        }
    }
}
正确的解决方案:

0 51 49
我当前的解决方案:

0 51 49
0 52 48
0 53 47
1 50 49
1 51 48
1 52 47
1 53 46
2 49 49
2 50 48
...
使用标签

      endItAll:
            for(int one=0; one<(a+1); one++){
                for(int two=0; two<(b+1); two++){
                    for(int three=0; three<(c+1); three++){
                        if((one+two+three)==n){
                            System.out.println(one+" "+two+" "+three);
                            break endItAll;
                        }
                    }
                }
            }
endItAll:
对于(int one=0;one使用标签

      endItAll:
            for(int one=0; one<(a+1); one++){
                for(int two=0; two<(b+1); two++){
                    for(int three=0; three<(c+1); three++){
                        if((one+two+three)==n){
                            System.out.println(one+" "+two+" "+three);
                            break endItAll;
                        }
                    }
                }
            }
endItAll:

对于(int one=0;oneNote:您不需要C的循环。只需从N中减去A+B即可找到C需要的值,然后检查它是否在0到C的范围内。啊,是的,我刚刚意识到我的解决方案有多慢,正在切换到减法解决方案,谢谢。注意:您不需要C的循环。只需从N中减去A+B即可找到CC值需要是,然后检查它是否在0到C的范围内。啊,是的,我刚刚意识到我的解有多慢,我正在切换到减法解,谢谢。