JavaPTA-学生类

有一个学生类的结构如下: class Student { private int no; private String name; private int score; public Student(int _no, String _name, int _score) { no = _no; name = _name; score = _score; } public int getNo() {return no;} public String getName() {return name;} public int getScore() {return score;} public void print(){ System.out.println(no + " “+name+” "+score); } }

请构造main函数完成如下功能: 从键盘中读入三个学生的信息,比较他们的成绩,按照成绩由高到低排列输出

输入描述:
三个学生的学号、姓名、成绩

输出描述:
由高到低排列输出的三个学生信息

裁判测试程序样例:

/*你的代码被嵌在这里*/

class Student {
	private int no;
	private String name;
        private int score;
	
	public Student(int _no, String _name, int _score) {
		no = _no;
		name = _name;
                score = _score;
	}
        public int getNo() {return no;}
        public String getName() {return name;}
        public int getScore() {return score;}
	
	public void print(){
		System.out.println(no + " "+name+" "+score);
	}
}

输入样例:
在这里给出一组输入。例如:

1 wang 89
2 liu 78
3 ma 90

输出样例:
在这里给出相应的输出。例如:

3 ma 90
1 wang 89
2 liu 78

答案:

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Student[] stu = new Student[3];
		Student t = new Student(0,null,0);
		for(int i = 0; i < 3; i ++ ) {
			stu[i] = new Student(sc.nextInt(), sc.next(), sc.nextInt());
		}
		for(int i=0;i<3;i++)
			for(int j=0;j<3;j++)
				if(stu[i].getScore()>stu[j].getScore()) {
					t=stu[i];
					stu[i]=stu[j];
					stu[j]=t;
				}
		for(int i = 0; i < 3; i ++) 
			stu[i].print();
		sc.close();
	}
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,构造函数是一个特殊的方法,用于创建和初始化一个对象。可以使用构造函数来指定对象的初始状态,为其成员变量赋初值,并执行一些必要的操作。 在ptajava2学生类中,构造函数可以用来初始化学生对象的属性。通常情况下,一个学生对象应该具有姓名、年龄、性别等基本信息。 构造函数的定义通常与类的名称相同,没有返回类型,并且在创建对象时自动调用。在学生类的构造函数中,我们可以传递参数来设置学生的姓名、年龄和性别,以便在对象创建时将其赋值给相应的属性。 例如,定义一个名为Student的类,可以定义一个构造函数如下: public class Student { private String name; // 学生姓名 private int age; // 学生年龄 private String gender; // 学生性别 // 构造函数 public Student(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } // 其他成员方法 // ... } 在上面的代码中,我们在Student类中定义了一个构造函数,它接受三个参数:name、age和gender,并将它们分别赋值给对应的成员变量。这样,在创建学生对象时,可以通过调用构造函数并传入相应的参数来初始化该对象的属性。 例如,可以使用以下代码创建一个名为"张三"、年龄为18岁、性别为"男"的学生对象: Student student = new Student("张三", 18, "男"); 通过构造函数,我们可以在创建对象时方便地设置学生的初始属性,使得对象的创建和初始化过程更加简洁和高效。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值