对于循环赢得';在循环java时不要在内部运行
我的程序中有一个while循环,它将无限循环,因为里面的for循环不会运行两次。我想从输入中找出总和为4的组合数,下面是我的代码:对于循环赢得';在循环java时不要在内部运行,java,Java,我的程序中有一个while循环,它将无限循环,因为里面的for循环不会运行两次。我想从输入中找出总和为4的组合数,下面是我的代码: Scanner scan = new Scanner(System.in); int n = scan.nextInt(); ArrayList<Integer> taxi = new ArrayList<Integer>(); for (int i=0; i<n; i++) { taxi.add(scan.nextInt());
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
ArrayList<Integer> taxi = new ArrayList<Integer>();
for (int i=0; i<n; i++) {
taxi.add(scan.nextInt());
}
int i = 0;
int total=0;
int tax=0;
int num = 0;
while (num<n) {
i=0;
for (i=0; i<n; i++) {
if (total+taxi.get(i)<=4) {
total+=taxi.get(i);
System.out.println(total);
num++;
}
}
tax++;
}
System.out.println("Taxis= " + tax);
Scanner scan=新的扫描仪(System.in);
int n=scan.nextInt();
ArrayList taxi=新的ArrayList();
对于(int i=0;i虽然您是代码,但您的问题似乎在于多次使用某些变量,如i,这会导致代码无法编译。请尝试使用更好的名称或更独特的名称,以防止将来出现这些问题。此外,我还建议不要在这种情况下经常将所有变量归零呃。最后,你的问题与变量n的用法有关,因为它仍然是一个固定的数字,在while循环中不会改变,这意味着它始终是真的。解决这个问题的最好方法是利用
break;
命令退出while循环或使用计数循环(如for循环)。
老实说,我认为下次问这些问题时,我会要求在适当的位置用打印行检查所有变量。现在是学习如何使用调试器的好时机。真的。你需要逐行检查每一行代码,检查变量值,并查看其行为。学习调试与学习语言。或者放入少量的System.out.println()。。。