FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
learnjava/InputSumAverage.java at main · michaelkolesidis/learnjava · GitHub
michaelkolesidis
/
learnjava
Public
Notifications
You must be signed in to change notification settings
Fork
7
Star
4
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
learnjava
/
InputSumAverage.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (40 loc) · 1.31 KB
Breadcrumbs
learnjava
/
InputSumAverage.java
Copy path
File metadata and controls
50 lines (40 loc) · 1.31 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* Input Sum Average
*
* Take double numbers as input and outputs their sum and their average value.
* Should be used with text file as input, as there is no exit
* condition for scanner.
*
*
* Use:
* $ cat text.txt | java Test > output.txt
*
* text.txt:
* 1
* 2
* 3
*
* Output: (in file output.txt)
* Sum: 6.0000
* Average: 2.0000
*/
import
java
.
util
.
Scanner
;
// Import the Scanner class
import
java
.
util
.
ArrayList
;
// Import the ArrayList class
class
InputSumAverage
{
public
static
void
main
(
String
[]
args
) {
ArrayList
<
Double
>
nums
=
new
ArrayList
<
Double
>();
// Create an ArrayList object
Scanner
scans
=
new
Scanner
(
System
.
in
);
// Create a Scanner object
while
(
scans
.
hasNextLine
()) {
// Scan until there are no more lines to scan
double
num
=
scans
.
nextDouble
();
// Parse double from scanned string
nums
.
add
(
num
);
// Add each scanned number to ArrayList
}
scans
.
close
();
// Stop scanning
double
sum
=
0
;
for
(
int
i
=
0
;
i
<
nums
.
size
();
i
++) {
sum
+=
nums
.
get
(
i
);
// Calculate the sum
}
double
average
=
sum
/
nums
.
size
();
System
.
out
.
printf
(
"Sum: %.4f
\n
"
,
sum
);
// Print the sum
System
.
out
.
printf
(
"Average: %.4f
\n
"
,
average
);
// Print the sum
}
}
Back
|
FazBrowse Home
|
New Git URL