7-5 程序改错1:对象与数组 (10 分)
修改如下程序的语法错误和逻辑错误,使程序运行结果如下:
//--------------------Main.java
public class Student {
private String name;
private double score;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public double getScore(){
return score;
}
public void setScore(double score){
this.score =score;
}
public void toString( ){
return this.name + "--" +this.score ;
}
}
public class Main {
public static void main(String args[]) {
String []name = {"Tom","Jim","Apple","Rose","Jack" ,"Lucy"};
double [] score = {98,76,85,66,72};
Student [] sGroup = new Student[ name.length ];
for( int i = 0 ; i < sGroup.length ; i++)
sGroup[i] = new Student (name[i], score[i]);
System.out.println("Student");
for( int i = 0 ; i < sGroup.length ; i++)
System.out.println(sGroup[i]);
System.out.println("end");
}
}
输入格式:
无。
输出格式:
Student
Tom--98.0
Jim--76.0
Apple--85.0
Rose--66.0
Jack--72.0
Lucy--0.0
end
代码如下
import java.util.*;
import java.util.Map.Entry;
//--------------------Main.java
class Student {
private String name;
private double score;
public Student(String string, double d) {
// TODO Auto-generated constructor stub
name=string;
score=d;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public double getScore(){
return score;
}
public void setScore(double score){
this.score =score;
}
public String toString( ){
return this.name + "--" +this.score ;
}
}
public class Main {
public static void main(String args[]) {
String []name = {"Tom","Jim","Apple","Rose","Jack" ,"Lucy"};
double [] score = {98,76,85,66,72};
Student [] sGroup = new Student[ name.length ];
for( int i = 0 ; i < sGroup.length ; i++) {
if(i<score.length) {
sGroup[i] = new Student (name[i], score[i]);
}else {
sGroup[i] = new Student (name[i], 0.0);
}
}
System.out.println("Student");
for( int i = 0 ; i < sGroup.length ; i++)
System.out.println(sGroup[i]);
System.out.println("end");
}
}
1.修改tostring函数返回值类型
2.增加两个参数的构造函数
3.防止数据越界,在main->for循环里加一个 if else