简单的类的构建和调用。
// An highlighted block
package com.demo;
public class MethodTest {
public static void main(String[] args) {
MethodTest sum = new MethodTest();
System.out.println("面积是:"+ sum.method(11, 9));
}
public int method(int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print("* ");
}
System.out.println();
}
return m * n;
}
}
下面展示一些 `内联代码片`。
//
/**
- 对象数组题目: 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
- 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
- 问题一:打印出3年级(state值为3)的学生信息。
- 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
- 要求: 将操作数组的功能封装到方法中。
*/
// An highlighted block
var foo = 'bar';
package com.demo;
/**
* 对象数组题目: 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
* 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
* 问题一:打印出3年级(state值为3)的学生信息。
* 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
* 要求: 将操作数组的功能封装到方法中。
*
*/
public class StudentTest {
public static void main(String[] args) {
// 声明student类型的数组
Student[] stud = new Student[20];
for (int i = 0; i < stud.length; i++) {
// 给数组元素赋值
stud[i] = new Student();
// 给Student对象的属性赋值
stud[i].number = i + 1;
// 假设年级 [1,3]
stud[i].state = (int) (Math.random() * (3 - 1 + 1) + 1);
// 成绩 [0,100]
stud[i].score = (int) (Math.random() * (100 - 1 + 1) + 1);
}
// 初始化封装
StudentTest test = new StudentTest();
// 问题一:打印出3年级(state值为3)的学生信息。
test.researchState(stud, 3);
System.out.println("********************");
// 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息 要求
test.sort(stud);
System.out.println("********************");
// 遍历学生数组
test.print(stud);
System.out.println("********************");
}
/**
* @Description 遍历Student[]数组的操作
*/
public void print(Student[] stud) {
for (int i = 0; i < stud.length; i++) {
System.out.println(stud[i].info());
}
}
/**
* @Description 查找Student[]数组中指定年级的学生信息
*/
public void researchState(Student[] stud, int state) {
for (int i = 0; i < stud.length; i++) {
if(stud[i].state == state){
System.out.println(stud[i].info());
}
}
}
/**
* @Description 查找Student[]数组中按照分数升序
*/
public void sort(Student[] stud) {
for (int i = 0; i < stud.length; i++) {
for (int j = 0; j < stud.length - i - 1; j++) {
if (stud[j].score > stud[j + 1].score) {
Student temp = stud[j];
stud[j] = stud[j + 1];
stud[j + 1] = temp;
}
}
}
}
}
class Student {
//public char[] info;
int number;// 学号
int state;// 年级
int score;// 分数
// 显示学生信息
public String info() {
return "学号:" + number + ",年级:" + state + ",分数:" + score;
}
}