forked from DSkilton/UdemyTimBurchalka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInputCalculator.java
66 lines (60 loc) · 1.96 KB
/
InputCalculator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.TimBuchalka;
//Write a method called inputThenPrintSumAndAverage that does not have any parameters. The method should
//not return anything (void) and it needs to keep reading int numbers from the keyboard. When the user
//enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY".
//
//XX represents the sum of all entered numbers of type int. YY represents the calculated average of all
//numbers of type long.
//
//EXAMPLES OF INPUT/OUTPUT:
//EXAMPLE 1:
//INPUT:
//1
//2
//3
//4
//5
//a
//
//OUTPUT
//SUM = 15 AVG = 3
//
//EXAMPLE 2:
//INPUT:
//hello
//
//OUTPUT:
//
//SUM = 0 AVG = 0
//
//TIP: Use Scanner to read an input from the user.
//TIP: Use casting when calling the round method since it needs double as a parameter.
//NOTE: Use the method Math.round to round the calculated average (double). The method round returns long.
//NOTE: Be mindful of spaces in the printed message.
//NOTE: Be mindful of users who may type an invalid input right away (see example above).
//NOTE: The method inputThenPrintSumAndAverage should be defined as public static like we have been doing so far in the course.
import jdk.internal.util.xml.impl.Input;
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
int sum = 0, count = 0, avg =0;
Scanner sc = new Scanner(System.in);
while (true) {
boolean isInt = sc.hasNextInt();
if (isInt) {
int value = sc.nextInt();
sum += value;
count++;
} else if (count == 0){
System.out.println("SUM = 0 AVG = 0");
break;
} else {
avg = sum/count;
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
sc.nextLine();
}
sc.close();
}
}