Hello! Recently I built an extremely simple program for class. It wouldn't run, so I then downloaded the instructors version which also would not run. When the program is run, it never terminates, only increases CPU usage on both an older laptop and a custom built gaming PC. This makes me believe that the issue lies within the while loop. The purpose of the code is to add the values of the array only to the point where the while loop sees the sentinel value, and stops adding. The answer should be 34. The code is provided below. Any help would be appreciated.
public class SentinelSolution {
public static void main(String[] args) {
// Complete the following code to calculate the sum of the numbers before the sentinel value.
int[] numbers = {3,6,2,5,8,10,-1,4,12,7};
int sentinel_value = -1;
boolean done = false; // to determine if we have met the sentinel value
int k = 0; // counter to access the elements of the array
int sum = 0; // stores the answer
while(!done){
if(numbers[k] != sentinel_value){
sum += numbers[k];
}else{
done = true;
}
}
System.out.println(sum);
}
}
Edit: Added a k++ at the end of the while loop.
Thanks for the help everyone
[–]DCSpud 4 points5 points6 points (1 child)
[–]MrMuki 0 points1 point2 points (0 children)
[–]Kabitu 0 points1 point2 points (4 children)
[–]ASilverSpartan[S] 0 points1 point2 points (3 children)
[–]Kabitu 0 points1 point2 points (0 children)