我在java中有一个数组列表,我可能需要输入一个代码来打印名为Artan的行,另一个是打印平均年龄。代码是这样的:
public class Student
{
public int nr;
public String name;
public int age;
public String sex;
public int tall;
public int weight;
Student(int nr, String name, int age, String sex, int tall, int weight) {
this.nr = nr;
this.name = name;
this.age = age;
this.sex = sex;
this.tall = tall;
this.weight = weight;
}
public static void main (String[] args)
{
Student[] arr;
arr = new Student[10];
arr[0] = new Student (1, "Artan", 19, "M", 175, 74);
arr[1] = new Student (2, "Ertan", 30, "M", 179, 80);
arr[2] = new Student (3, "Jin", 25, "M", 175, 75);
arr[3] = new Student (4, "Isabella", 28, "F", 165, 54);
arr[4] = new Student (5, "Anita", 21, "F", 164, 53);
arr[5] = new Student (6, "Daniel", 32, "M", 180, 82);
arr[6] = new Student (7, "Anton", 32, "M", 178, 75);
arr[7] = new Student (8, "Miroslav", 40, "M", 186, 83);
arr[8] = new Student (9, "Michael", 50, "M", 190, 95);
arr[9] = new Student (10, "Katarina", 62, "F", 160, 74);
for (int i = 0; i <= arr.length; i++)
System.out.println("Student List: "+ arr[i].nr+ " " + arr[i].name+" "+ arr[i].age +" "+ arr[i].sex+" "+ arr[i].tall+"cm "+ arr[i].weight+"kg");
}
}
我应该知道什么,写什么代码?
答案 0 :(得分:0)
我会@Override toString()
@Override
public String toString() {
return "Student{" + "nr=" + nr + ", name=" + name + ", age=" + age + ", sex=" + sex + ", tall=" + tall + ", weight=" + weight + '}';
}
并使用Streams
:
Stream.of(arr)
.filter(x -> x.name.equals("Artan"))
.forEach(System.out::println);
并计算所有学生的平均年龄:
Double avg = Stream.of(arr)
.mapToDouble(x -> x.age)
.average()
.getAsDouble();
System.out.println(String.format("Average: %s", avg));
答案 1 :(得分:0)
for (int i = 0; i < arr.length; i++){
if (arr[i].name.equals("Artan")){
System.out.println("Student List: "+ arr[i].nr+ " " + arr[i].name+" "+ arr[i].age +" "+ arr[i].sex+" "+ arr[i].tall+"cm "+ arr[i].weight+"kg");
}
}
您还可以覆盖toString
方法并打印出学生对象:
System.out.println("Student : " + arr[i]);