zoukankan      html  css  js  c++  java
  • 对象数组题目

    * 对象数组题目:
    * 定义类Student,包含三个属性:学号number(int),年级state(int),成绩 score(int)。
    * 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
    * 问题一:打印出3年级(state值为3)的学生信息。
    * 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

    本题代码实现如下:

    public class OOP1 {

      public static void main(String[] args) {
      //创建Student的对象
      Student[] stus = new Student[20];
      for (int i = 0; i < stus.length; i++) {
        //创建二十个学生对象
        stus[i] = new Student();
        //创建学号
        stus[i].number = (i + 1);
        //使用随机数创建年级[1,6]
        stus[i].state = (int)(Math.random()*(6-1+1)+1);
        //使用随机数创建成绩[0-100]
        stus[i].score = (int)(Math.random()*(100+1));
      }
      //创建对象
      OOP1 test = new OOP1();
      //调用方法,打印学生信息
      test.printAll(stus);
      System.out.println("**************************************");
      //调用方法printState,打印某一个年级的学生信息
      test.printState(stus, 5);
      System.out.println("**************************************");
      //调用方法Sort,对成绩进行冒泡排序
      test.Sort(stus);
      test.printAll(stus);//打印
    }
    /**
    * 遍历stus
    * @param stus
    */
    public void printAll(Student[] stus){
      for (int i = 0; i < stus.length; i++) {
        System.out.println("学号为:"+stus[i].number+"年级为:"+
          stus[i].state+"成绩为:"+stus[i].score);
      }
    }
    /**
    * 打印某一个年级的学生信息
    * @param stus
    * @param s 需要打印的年级
    */
    public void printState(Student[] stus, int s){
      for (int i = 0; i < stus.length; i++) {
        if(stus[i].state == s){
          System.out.println("学号为:"+stus[i].number+"年级为:"+
            stus[i].state+"成绩为:"+stus[i].score);
        }
      }
    }
    /**
    *冒泡排序
    * @param stus
    */
    public void Sort(Student[] stus){
      for (int i = 0; i < stus.length - 1; i++) {
        for (int j = 0; j < stus.length - 1 - i; j++) {
          if(stus[j].score > stus[j + 1].score){
            Student temp = stus[j];
            stus[j] = stus[j + 1];
            stus[j + 1] = temp;
          }
        }
      }
    }

    }

    class Student{
      int number;//学号
      int state;//年级
      int score;//成绩

    }

  • 相关阅读:
    华为机考--约瑟夫问题
    华为机考--字符串压缩
    2014华为校招机考模拟--求最大递增数
    2014华为校招机考模拟--记票统计
    插入排序与归并排序的C#实现
    步入C#--hello world
    shell 命令用法
    About compiling some source code on centos
    ubuntu Install packages
    ssh命令
  • 原文地址:https://www.cnblogs.com/zhou-x/p/10877605.html
Copyright © 2011-2022 走看看