Purpose To test the ability to write loops using Java Directions and example Wri
ID: 3870342 • Letter: P
Question
Purpose
To test the ability to write loops using Java
Directions and example
Write a program that asks the user to enter numbers and keeps a running total (the sum of all of the numbers the user has entered so far). The program should stop when the running total becomes greater than 100. When the program stops, it should tell the user how many numbers they entered before the sum became greater than 100. Below are some examples:
Your spacing, capitalization, and wording must be exactly as shown above.
Explanation / Answer
Please find my code.
import java.util.Scanner;
public class LoopTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
int total = 0;
int count = 0;
while(total < 100) {
System.out.print("Enter a number: ");
num = scanner.nextInt();
total = total + num;
count++;
}
scanner.close();
System.out.println("You entered "+(count-1)+" values before the total was greater than 100");
}
}
/*
Sample run:
Enter a number: 14
Enter a number: 18
Enter a number: 27
Enter a number: 74
You entered 3 values before the total was greater than 100
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.