感觉面向对象中的一维数组像二维数组一样,一个元素中可以存好多数据,建议第二关多看看
掌握知识点(1,2)
- 对象之数组静态赋值
- 对象数组定义
- split()方法
- Double.valueOf()方法,字符串转Double
- 面向对象数组概念
通关源码(1)
public class Dog {
private String name;
private String type;
private int age;
private String hobby;
public Dog(){
}
public Dog(String name, String type, int age, String hobby) {
this.name = name;
this.type = type;
this.age = age;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public void info(){
System.out.printf("小狗名称:%s\n品种:%s\n小狗年龄:%d\n小狗爱好:%s\n",name,type,age,hobby);
}
public static void main(String[] args) {
Dog d1 = new Dog("Tom", "哈士奇",2,"拆家");
Dog d2 = new Dog("jerry", "中华田园犬",3,"护家");
Dog d3 = new Dog("旺财","柯基",2,"吃喝玩");
Dog []dog = new Dog[]{d1,d2,d3};
for (int i = 0; i < dog.length; i++) {
dog[i].info();
}
}
}
通关源码(2)
import java.util.Scanner;
public class Student {
private String name;
private String num;
private double grades;
public Student(String name, String num, double grades) {
this.name = name;
this.num = num;
this.grades = grades;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public double getGrades() {
return grades;
}
public void setGrades(double grades) {
this.grades = grades;
}
public static void main(String[] args) {
Student[] stu = new Student[3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < stu.length; i++) {
String str = scanner.next();
stu[i] = new Student(str.split(",")[0],str.split(",")[1]
,Double.valueOf(str.split(",")[2]));
}
for (int i = 0; i < stu.length; i++) {
System.out.printf("姓名:" + stu[i].getName() + "\t学号:" + stu[i].getNum() + "\t成绩:" + stu[i].getGrades() + "\n");
}
}
}
|