public class StudentDemo { public static void main(String[] args) { //声明Student类数组(含3个元素) Student[] students = new Student[3]; Scanner in = new Scanner(System.in); //输入3个对象存入数组,其中一个为Student类的对象,一个StudentSJ类的对象,一个StudentZZ类的对象 students[0] = new Student(in.next(), in.next(), in.nextDouble(), in.nextDouble(), in.nextDouble()); students[1] = new StudentSJ(in.next(), in.next(), in.nextDouble(), in.nextDouble(), in.nextDouble(), in.next()); students[2] = new StudentZZ(in.next(), in.next(), in.nextDouble(), in.nextDouble(), in.nextDouble(), in.next()); //将方法testScore()发送给数组中的每一个元素,输出结果,并分析具体执行的是哪一个类中的方法 for (int i = 0; i < students.length; i++) { System.out.println(students[i].toString()); } System.out.println(); //比较StudentSJ类对象和StudentZZ类对象的总成绩,输出结果 if (students[1].compare(students[2]) > 0) { System.out.println( "'s total score is more than Wangwu"); } else if (students[1].compare(students[2]) == 0) { System.out.println("李四的总成绩和王五相同"); } else { System.out.println(students[1] + "'s total score is less than " + students[2]); } } }如何在输出时仅输出数组的某一项
时间: 2024-02-04 22:01:43 浏览: 18
如果你想在输出时仅输出数组的某一项,可以在输出时使用数组的下标来定位某一项,例如:
```java
System.out.println(students[1].getName() + "'s total score is less than " + students[2].getName());
```
这里使用了`students[1].getName()`和`students[2].getName()`来仅输出数组中第二项(`students[1]`)和第三项(`students[2]`)的姓名。你可以通过类似这样的方式来输出数组中的其他属性。
相关问题
public class Student{ private String name; public void setName(char n) { name=n; } public void getName(){ return name; } public static void main(String args){ new Student(); } }
该代码有几个错误,应该如下修改:
1. 在 `setName` 方法的参数类型应该是 `String` 而不是 `char`。
2. `getName` 方法的返回类型应该是 `String` 而不是 `void`。
3. `main` 方法中的参数应该是一个字符串数组,即 `String[] args`。
4. 在 `main` 方法中,创建 `Student` 对象时应该使用 `new Student()`。
正确的代码如下:
```
public class Student {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public static void main(String[] args) {
Student s = new Student();
}
}
```
这个代码创建了一个 `Student` 类,它有一个私有的 `name` 字段和两个公共方法 `setName` 和 `getName` 来设置和获取 `name` 字段的值。在 `main` 方法中,它创建了一个 `Student` 对象并将其赋值给变量 `s`。
public class Student{ private String name; public void setName(char n) { name=n; } public void getName(){ return name; } public static void main(String args){ new Student(); } }哪部分错误
这段 Java 代码有几个错误:
1. 在 setName 方法中,参数应该是 String 类型而不是 char 类型,因为 name 是一个字符串类型的变量。应该改为 `public void setName(String n) { name = n; }`。
2. 在 getName 方法中,应该指定返回值类型为 String 而不是 void,因为该方法的作用是获取字符串类型的 name 变量的值。应该改为 `public String getName() { return name; }`。
3. 在 main 方法中,应该使用正确的参数类型 String[] 而不是 String。应该改为 `public static void main(String[] args) { new Student(); }`。
因此,修正后的代码如下:
```
public class Student {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public static void main(String[] args) {
new Student();
}
}
```