The first line is the number of data sets.
The second line is the data, where the first is the amount of data. and after that is data . such as
1
after specify amount of set. we have to input data 1 set follow below.
3 1 2 3
first number is How many data you have to input, for second ,third, and fourth is input.
And other example :
2
2 1 2
3 2 3 4
My problem : I don't now how to make input after I specify amount if set(first line) . I don't know how to do after input first line.
import java.util.Scanner;
public class average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int set = sc.nextInt();
int count = 0, i = 1;
double sum = 0 ;
double avg;
String str_num = sc.nextLine();
String[] arr = str_num.split(" ");
while (Integer.parseInt(arr[i]) != -1){
sum = Integer.parseInt(arr[i]);
i ;
count ;
}
avg = sum / count;
System.out.printf("%.3f", avg);
}
}
CodePudding user response:
public class Average {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
List<int[]> data = readData(scan);
double avg = calcAvg(data);
System.out.format(Locale.ENGLISH, "%.3f\n", avg);
}
private static List<int[]> readData(Scanner scan) {
int total = scan.nextInt();
List<int[]> data = new ArrayList<>(total);
for (int i = 0; i < total; i ) {
int[] dataLine = new int[scan.nextInt()];
for (int j = 0; j < dataLine.length; j )
dataLine[j] = scan.nextInt();
data.add(dataLine);
}
return data;
}
private static double calcAvg(List<int[]> data) {
int sum = 0;
int count = 0;
for (int[] dataLine : data) {
count = dataLine.length;
sum = Arrays.stream(dataLine).sum();
}
return count == 0 ? 0 : (double)sum / count;
}
}
Demo:
2
2 1 2
3 2 3 4
2.400
CodePudding user response:
I have written the instructions to get input, modify the needed data type and perform needed operations
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// number of dataSets
int dataSets = sc.nextInt();
// getting input for each dataSet
for(int i = 0; i < dataSets ; i ) {
// number of data in each dataset
int n = sc.nextInt();
int[] arr = new int[n 1];
arr[0] = n; // first data indicates number of data in that dataset
for(int j = 1 ; j < arr.length ; j ) {
// getting the input data
arr[j] = sc.nextInt();
}
System.out.println(Arrays.toString(arr));
}
}
}