7-5 程序改错1:对象与数组 (10 分) pta

30 篇文章 6 订阅

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

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值