There's a while loop in my program that will loop infinitely because the for loop inside won't run twice. I want to find the number of combinations that will have a sum of 4 from input and here's my code:
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);
looking though you're code it seems your issue lies in the usage of some of your variables such as I multiple times which causes the code to not compile. try using better names or more unique names in order to prevent these issues in future. as well as that I would also advise not zeroing all of your variables so often in such a manner. Finally your issue has to do with your usage of the variable n as it remains a fixed number which will not change in the while loop meaning it will always be true. the best way to fix this is to utilize the
break;
command to exit the while loop or to use a counted loop like a for loop. In my honest opinion i would request that when asking these questions next time check all the variables with a print line in the appropriate spot.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.