KaiquanMah commited on
Commit
68e0d9e
·
verified ·
1 Parent(s): 9c456c5

Create 12b. Sum, max of numbers

Browse files
Week 1: Types, condition clauses and loops/12b. Sum, max of numbers ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sum of the number and maximum
2
+ 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.
3
+
4
+ Example output:
5
+
6
+ Give a number: 1
7
+ Give a number: 2
8
+ Give a number: 3
9
+ Give a number: -1
10
+ Sum: 6
11
+ Maximum: 3
12
+
13
+
14
+
15
+ =======================================
16
+
17
+ import java.util.Random;
18
+ import java.util.Scanner;
19
+
20
+
21
+
22
+ public class Test{
23
+ public static void main(String[] args){
24
+ final Random r = new Random();
25
+
26
+
27
+
28
+ Scanner reader = new Scanner(System.in);
29
+ int sum = 0;
30
+ int max = 0;
31
+
32
+
33
+ while (true) {
34
+ System.out.print("Give a number: ");
35
+ int num = Integer.valueOf(reader.nextLine());
36
+
37
+ // break the loop if '-1'
38
+ if (num == -1) {
39
+ break;
40
+ }
41
+
42
+ // cumulative sum
43
+ sum += num;
44
+ // update 'max'
45
+ if (max < num) {
46
+ max = num;
47
+ }
48
+
49
+ }
50
+ System.out.println("Sum: "+sum);
51
+ System.out.println("Maximum: "+max);
52
+
53
+
54
+
55
+ }
56
+ }
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+ Test number 1
66
+ Give a number: 2
67
+ Give a number: 3
68
+ Give a number: 4
69
+ Give a number: 5
70
+ Give a number: -1
71
+ Sum: 14
72
+ Maximum: 5
73
+
74
+ Test number 2
75
+ Give a number: 10
76
+ Give a number: 12
77
+ Give a number: 14
78
+ Give a number: 16
79
+ Give a number: -1
80
+ Sum: 52
81
+ Maximum: 16
82
+
83
+ Test number 3
84
+ Give a number: 9
85
+ Give a number: 9
86
+ Give a number: 9
87
+ Give a number: 9
88
+ Give a number: 9
89
+ Give a number: -1
90
+ Sum: 45
91
+ Maximum: 9
92
+
93
+
94
+