Java 对象数组的传递

 1 package Texts.News.copy;
 2 /*
 3  * 测试类,在这里运行 (添加学生成绩)
 4  */
 5 public class Main {
 6 
 7     public static void main(String[] args) {
 8 
 9         IS is = new IS();            //创建学生操作对象
10         Student[] n = is.input();    //接返回的对象数组
11         
12         System.out.println("\n        学生信息");
13         System.out.println("\n编号\t成绩\t  及格\n");
14         
15         for (int i=0; i<n.length; i++) {    //循环输出对象里的编号、成绩、是否及格
16             System.out.println(n[i].number+"\t"+n[i].score+"\t   "+n[i].pass);
17         }
18         
19     }
20 
21 }

 1 package Texts.News.copy;
 2 /*
 3  * 学生类
 4  */
 5 public class Student {
 6 
 7     int number ;    //学号
 8     int score;      //成绩
 9     String pass;    //是否及格
10 }

 1 package Texts.News.copy;
 2 
 3 import java.util.Scanner;
 4 /*
 5  * 学生操作类会返回一个对象数组。
 6  */
 7 public class IS {
 8 
 9     public Student [] input() {    
10         
11         int n = 0;    //数组长度
12         
13         for (;;) {    //此循环为错误处理
14             
15             Scanner input = new Scanner(System.in);    //创建键盘输入对象
16             System.out.print("录入几个信息:");
17             
18             if (input.hasNextInt()) {    //错误处理,如果输入的是数字if通过,否则else
19                 n = input.nextInt();
20                 break;
21             }
22             else {
23                 System.out.println("请正确输入!");
24                 continue;
25             }
26 
27         }
28 
29         Student [] s = new Student [n];    //创建一个对象数组,用于存for循环每次new出来的对象。
30         
31         for (int i=0; i<s.length; i++) {
32             
33             Scanner input = new Scanner(System.in);    //创建键盘输入对象
34             Student stu = new Student();           //创建学生对象,每循环一次就new一个新对象,添加的信息也就放到不同的对象里去了。
35 
36             System.out.print("\n第"+(i+1)+"位学生编号:");
37             stu.number = input.nextInt();
38             System.out.print("第"+(i+1)+"位学生成绩:");
39             stu.score = input.nextInt();
40             
41             if (stu.score>=80) {        //判断成绩是否及格,大于等于80分两个勾大于等于60分一个勾
42                 stu.pass = "√√";
43             }
44             else if (stu.score>=60){
45                 stu.pass = "√";
46             }
47             else {
48                 stu.pass = "×";
49             }
50             
51             s[i] = stu;    //把new出来的新对象添加到数组对应的位置,第一次new的就是第一个位置脚标i=0,i随着循环而增加。for循环结束数组里就填满了对象。
52             
53         }
54         return s;        //把填满对象的数组返回回去。
55         
56     }
57 }

 

 

posted @ 2015-01-10 19:37  星空夜  阅读(843)  评论(0编辑  收藏  举报