Java基础## 面向对象## 练习
1.利用面向对象的编程方法,设计类Circle计算圆的面积
package lyj.java;
public class CircleTest {
public static void main (String[] args){
Circle c1 = new Circle();
c1.radius = 2.5;
double area = c1.findArea();
System.out.println(area);
}
}
class Circle {
//属性
double radius;
//求圆的面积
public double findArea ()
{
double area = Math.PI * radius * radius;
return area;
}
}
2. method方法提供m和n两个参数,方法中打印一个m * n的 * 型矩形,并计算该矩形的面积, 将其作为方法返回值。在main方法中调用该方法,接收返回的面积值并打印。
3. 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息,
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
public class Exer3Test {
public static void main (String[] args){
Exer3Test test = new Exer3Test();
int area = test.method(10,8);
System.out.println("面积为:" + area);
}
public int method (int m,int n){
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
System.out.println("* ");
}
System.out.println();
}
return m * n;
}
}
package lyj.java;
public class ExerTest4 {
public static void main(String[]args){
//声明Student类型的数组
Student[] stus = new Student[20];
for(int i = 0;i < stus.length;i++){
//给数组元素赋值
stus[i] = new Student();
//引用类型的变量只能存储两内值:null或地址值
//给Student对象的属性赋值
stus[i].number=(i+1);
stus[i].state = (int)(Math.random()*(6-1+1)+1);
stus[i].score = (int)(Math.random()*(100-0+1)+0);
}
//问题一:打印出3年级(state值为3)的学生信息
for(int i = 0;i < stus.length;i++){
if(stus[i].state == 3){
System.out.println(stus[i].info());
}
}
System.out.println();
//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
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;
}
}
}
for(int i = 0;i < stus.length;i++){
System.out.println(stus[i].info());
}
}
}
class Student {
int number;
int state;
int score;
//显示学生信息的方法
public String info(){
return "学号:" + number +",年级:" + state +",成绩:" + score;
}
}