Rookie Java question - Scanner, int and user input

Viewed 29

Hello there fellow Overflowers!

I'm getting started with Java and want to create a small program where it's possible to type in 5 numbers and get the sum and average printed out. The program runs and does it's job, but I feel that there must be a way smarter method / way then what I've done.

import java.util.Scanner;
public class Calc {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("5 random numbers");

        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int num3 = input.nextInt();
        int num4 = input.nextInt();
        int num5 = input.nextInt();
        int sum = num1 + num2 + num3 + num4 + num5;
        int avg = (num1 + num2 + num3 + num4 + num5)/5;
        System.out.println("Sum is" + sum + " and the average is " + avg);```

Is it possible to declare all the numbers in one line or something?

1 Answers

You can use BufferedReader. Try this. Here, you need to mention all numbers in a single line.

Ex: 1 2 3 4 5

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] values = line.split(" ");
int[] arr = new int[values.length];
int sum=0;
for (int i = 0; i < values.length; i++) {
   arr[i] = Integer.parseInt(values[i]);
   sum+=arr[i];
}
double avg = sum/arr.length;
System.out.println("Sum is" + sum + " and the average is " + avg);
Related