Spaces:
Running
Running
| // Sum of the number and maximum | |
| Write a program that asks the user to enter integers. When the user enters the number -1, the program terminates and prints the sum of all numbers entered (before -1) and the largest number entered. | |
| Example output: | |
| Give a number: 1 | |
| Give a number: 2 | |
| Give a number: 3 | |
| Give a number: -1 | |
| Sum: 6 | |
| Maximum: 3 | |
| ======================================= | |
| import java.util.Random; | |
| import java.util.Scanner; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| Scanner reader = new Scanner(System.in); | |
| int sum = 0; | |
| int max = 0; | |
| while (true) { | |
| System.out.print("Give a number: "); | |
| int num = Integer.valueOf(reader.nextLine()); | |
| // break the loop if '-1' | |
| if (num == -1) { | |
| break; | |
| } | |
| // cumulative sum | |
| sum += num; | |
| // update 'max' | |
| if (max < num) { | |
| max = num; | |
| } | |
| } | |
| System.out.println("Sum: "+sum); | |
| System.out.println("Maximum: "+max); | |
| } | |
| } | |
| Test number 1 | |
| Give a number: 2 | |
| Give a number: 3 | |
| Give a number: 4 | |
| Give a number: 5 | |
| Give a number: -1 | |
| Sum: 14 | |
| Maximum: 5 | |
| Test number 2 | |
| Give a number: 10 | |
| Give a number: 12 | |
| Give a number: 14 | |
| Give a number: 16 | |
| Give a number: -1 | |
| Sum: 52 | |
| Maximum: 16 | |
| Test number 3 | |
| Give a number: 9 | |
| Give a number: 9 | |
| Give a number: 9 | |
| Give a number: 9 | |
| Give a number: 9 | |
| Give a number: -1 | |
| Sum: 45 | |
| Maximum: 9 | |