跳到主要内容

练习题1

· 阅读需 2 分钟
季冠臣
后端研发工程师

简单的Java有关数组、循环的练习题

知识点:数组、循环、if、边界

创建100个学生对象,id编号为1-100 把编号可以大于60的归为二组,其它归为一组

知识点:switch

定义一个方法,给1-4其中一个数字,返回春夏秋冬字符串,不命中则返回 错误季节。

知识点:static、数组、循环

定义一个Dog类,里面含有age静态变量初始值为10,有一个name成员属性,有一个changAge方法,使age自增1,创建含5个的dog数组,获取数组角标为3的dog对象,调用两次changAge方法,最后打印5个dog对象的age分别为多少?

public class AnswerTest {

public static void main(String [] args){
// test1();

//test2();
test3();
}

public static void test3(){
Dog [] dogs = new Dog[5];

for(int i=0; i<5; i++){
Dog dog = new Dog();
dog.setName("旺财"+i);
dogs[i] = dog;
}

Dog dog = dogs[3];
dog.changeAge();
dog.changeAge();

for (Dog d : dogs){
System.out.println("名称="+d.getName() + ", age="+d.getAge());
}


}

public static void test2(){
int season = 10;

String content;

switch (season){
case 1:content="春";
break;

case 2:content="夏";
break;

case 3:content="秋";
break;

case 4:content="冬";
break;

default: {
content="错误季节";
System.out.println("default 执行");
}
}

System.out.println(content);

}

public static void test1(){
Student[] arr1 = new Student[60];
int arr1Index = 0;

Student[] arr2 = new Student[40];
int arr2Index = 0;

for(int i=0; i<100; i++){
int num = i+1;
Student student = new Student();
student.setId(num);
if(num > 60){
arr2[arr2Index] = student;
//arr2Index = arr2Index +1;
arr2Index++;
}else {
arr1[arr1Index] = student;
arr1Index++;
}
}


for(Student s: arr1){
System.out.println(s.getId());
}

System.out.println("============");
for(Student s: arr2){
System.out.println(s.getId());
}

}
}
public class Student {

private int id;

public int getId(){
return id;
}

public void setId(int id){
this.id = id;
}
}

public class Dog {

public static int age =10;

private String name;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void changeAge(){
age++;
}

public int getAge(){
return age;
}

}

浏览量:加载中...