Skip to content

Instantly share code, notes, and snippets.

@amir1376
Created June 29, 2020 11:56
Show Gist options
  • Save amir1376/182b414cfdef6470201c75562c9bb34a to your computer and use it in GitHub Desktop.
Save amir1376/182b414cfdef6470201c75562c9bb34a to your computer and use it in GitHub Desktop.
simpe average in java for beginners
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Average {
public static void main(String[] args) {
ArrayList<Student> students= new ArrayList<>();
Student amir = new Student(12.0, 12.5, 19.0, 20.0);
Student ali = new Student(15.5, 13.25, 14.0, 5.5);
Student elham = new Student(16.0, 17.5, 17.0, 20.0);
Student azam = new Student(15.0, 18.5, 17.0, 19.0);
students.add(amir);
students.add(ali);
students.add(elham);
students.add(azam);
ArrayList<Double> aveScores=new ArrayList<>();
for (Student student : students) {
aveScores.add(ave(student.scores));
}
System.out.println("average of all student scores is:");
System.out.println(ave(aveScores));
}
public static double ave(List<Double> nums) {
double sum = 0;
for (double n : nums) {
sum += n;
}
return sum / nums.size();
}
public static class Student{
public List<Double> scores=new ArrayList<>();
public Student(Double... scores){
this.scores.addAll(Arrays.asList(scores));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment