2021. 4. 3. 23:47ㆍJava programming
Wrtie a mtehod called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything 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.
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
double XX = 0;
double YY = 0;
int counter = 0;
while (true){
boolean isAnInt = scanner.hasNextInt();
if (isAnInt){
int order = counter + 1;
int number = scanner.nextInt();
XX += number;
YY = XX / order;
counter++;
} else {
break;
}
}
System.out.println("SUM = " + Math.round(XX) + " AVG = " + Math.round(YY));
scanner.close();
}
}
Regardless of the algorithms this exercise requires, it was the very first time using the class called Scanner.
I have to say it's quite intriguing to input whatever variables are and use them within the functions I programmed.
And this moment got me think "Well.. okay, this is the real start of communicating with the computer and the first step of programming as a toddler!"
In order to use such that big util, we need to import the util and initialise it by typing 'import java.util.Scanner;' above a class (actually it will be automatically created once you initialise it) and 'Scanner scanner = new Scanner;' in a method.
'Scanner' with the captial letter S refers to input functioning util, while we have the next 'scanner' meaning we're going to refer 'Scanner' to 'scanner'.
And that is equal to 'new Scanner' declares the util is set.
Well.. still not familar with the usage but I guess probably practices over time only make it easier.
'Java programming' 카테고리의 다른 글
Coding Exercise 29: Sum Calculator (0) | 2021.04.04 |
---|---|
Coding Exercise 28: Paint Job (0) | 2021.04.04 |
Coding Exercise 26: Diagonal Star (0) | 2021.04.03 |
Coding Exercise 25: Largest Prime (0) | 2021.04.02 |
Coding Exercise 24: Flour Park Problem (0) | 2021.04.01 |