簡體   English   中英

for循環不會在while循環java中運行

[英]for loop won't run inside while loop 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());
}

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

雖然你是代碼,但你的問題似乎在於你的一些變量的使用,比如 I 多次導致代碼無法編譯。 嘗試使用更好的名稱或更獨特的名稱,以防止將來出現這些問題。 除此之外,我還建議不要以這種方式經常將所有變量歸零。 最后,您的問題與您對變量 n 的使用有關,因為它仍然是一個固定數字,在 while 循環中不會改變,這意味着它始終為真。 解決此問題的最佳方法是利用

break;

命令退出 while 循環或使用計數循環,如 for 循環。 老實說,我會要求下次問這些問題時,在適當的位置用打印線檢查所有變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM