2011. 6. 15. 20:47

자바(Java) 객체를 배열로 처리하기

자바에는 구조체가 없으므로 무조건 객체로 처리를 해야 한다. 객체도 배열로 처리할 수 있는데 이렇게 하려면 배열로 선언된 수 만큼 객체의 인스턴스를 생성해야 한다. 그 수가 많을 때에는 for문을 쓰면 된다.

  1: import java.util.Scanner ;
  2: 
  3: class Student {
  4:  private String name ;
  5:  private int age ;
  6:  private String phoneNumber ;
  7:  private String specialSkill ;
  8:  private String address ;
  9: 
 10:  public void setName(String name) {
 11:   this.name = name ;
 12:  }
 13: 
 14:  public void setAge(int age) {
 15:   this.age = age ;
 16:  }
 17: 
 18:  public void setPhoneNumber(String phoneNumber) {
 19:   this.phoneNumber = phoneNumber ;
 20:  }
 21: 
 22:  public void setSpecialSkill(String specialSkill) {
 23:   this.specialSkill = specialSkill ;
 24:  }
 25: 
 26:  public void setAddress(String address) {
 27:   this.address = address ;
 28:  }
 29: 
 30:  public void print() {  
 31:   System.out.println("이  름 : " + this.name) ;
 32:   System.out.println("나  이 : " + this.age) ;
 33:   System.out.println("연락처 : " + this.phoneNumber) ;
 34:   System.out.println("주특기 : " + this.specialSkill) ;
 35:   System.out.println("사는곳 : " + this.address + "\n") ;
 36:  }
 37: }
 38: 
 39: public class StudentClassArrayTest {
 40:  public static void main(String[] args)  {
 41:   Scanner scan = new Scanner(System.in) ;
 42:   int inputNumber ;
 43: 
 44:   System.out.print("입력 인원 : ") ;
 45:   inputNumber = scan.nextInt() ;
 46: 
 47:   Student[] student = new Student[inputNumber] ;  
 48: 
 49:   System.out.println("\n학생 정보 입력") ;
 50:   System.out.println("--------------------") ;
 51: 
 52:   for (int i = 0 ; i < student.length ; i++) {
 53:    student[i] = new Student() ;
 54: 
 55:    System.out.print("이  름 : ") ;
 56:    student[i].setName(scan.next()) ;
 57: 
 58:    System.out.print("나  이 : ") ;
 59:    student[i].setAge(scan.nextInt()) ;
 60: 
 61:    System.out.print("연락처 : ") ;
 62:    student[i].setPhoneNumber(scan.next()) ;
 63:    scan.nextLine() ;
 64: 
 65:    System.out.print("주특기 : ") ;
 66:    student[i].setSpecialSkill(scan.nextLine()) ;
 67: 
 68:    System.out.print("사는곳 : ") ;
 69:    student[i].setAddress(scan.nextLine()) ;
 70:    System.out.println() ;
 71:   }
 72: 
 73:   System.out.println("\n학생 정보 출력") ;
 74:   System.out.println("====================") ;
 75:   
 76:   for (int i = 0 ; i < student.length ; i++) {
 77:    student[i].print() ;
 78:   }
 79:  } //main
 80: }

Comment 0