Java教程

PAT 1004 JAVA编写

本文主要是介绍PAT 1004 JAVA编写,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

PAT 1004 JAVA编写

PAT 1004 JAVA编写


文章目录

  • PAT 1004 JAVA编写
  • 一、题目理解
  • 二、难点解决
    • 1.方法一
    • 2.方法二
  • 关于代码
  • 代码来源
  • 思考
  • 一些方法函数


一、题目理解

一开始感觉很简单,就是认为是数组比大小,具体是Student对象里score属性的对比。但是在实践的时候出现各种问题。问题应该是**对象数组的创建,并对对象属性的赋值**。

二、难点解决

经查阅资料,以下两种方式

1.方法一

代码如下(示例):

public class Student{
	String name;
	int age;
}

public class StudentTest{
	public static void main(String[] args){
		Student[] stu = new Studnet[5];
		Student stu0 = new Student();
		stu0.name = "陈平安";
		stu0.age = 12;
		stu[0] = stu0;
	}
}

2.方法二

代码如下(示例):

public class Student{
	String name;
	int age;
}

public class StudentTest{
	public static void main(String[] args){
		Student[] stu = new Studnet[5];
		stu[0] = new Student();
		stu[0].name = "陈平安";
		stu[0].age = 18;
	}
}

关于代码

import java.util.Scanner;
public class Main {
    private String name;
    private String sID;
    private int score;

//    public String getName() {
//        return name;
//    }
//    public void setName(String name) {
//        this.name = name;
//    }
//    public String getsID() {
//        return sID;
//    }
//    public void setsID(String sID) {
//        this.sID = sID;
//    }
//    public int getScore() {
//        return score;
//    }
//    public void setScore(int score) {
//        this.score = score;
//    }

    public static void sortByScore(Main []stu,int n){
        Main min,max;
        min = stu[0];
        max = stu[0];
        for(int i = 1; i < n;i++){
            if(min.score>stu[i].score){
                min = stu[i];
            }
            if(max.score<stu[i].score){
                max = stu[i];
            }
        }
        System.out.println(max.name+" "+max.sID);
        System.out.println(min.name+" "+min.sID);
    }

    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        Main[] stu = new Main[n];
        String temp = "";
        for(int i = 0;i < n;i++){
            temp = sc.nextLine();
            String [] student = temp.split(" ");
            stu[i] = new Main();
            stu[i].name = student[0];
            stu[i].sID = student[1];
            stu[i].score = Integer.parseInt(student[2]);
        }
        sc.close();
       	sortByScore(stu, n);
    }
}

代码来源

[https://www.pianshen.com/article/86601207410/]

思考

首先,观察题目,必须要有一个Student类,成员变量包括:姓名,学号,成绩。其次还应该有main主函数,sort排序函数,鉴于OJ,它们必须写在同一个文件中。

一些方法函数

split();字符串的分割,返回值是String[]	

Integer.parseInt():转换为int型数组

这篇关于PAT 1004 JAVA编写的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!