본문 바로가기

Learning/JAVA

배열안에 객체 만들기 (이차원 배열/입력 클래스, 출력클래스 분리)

  • Drink, DrinkMain 클래스 구분하여 차종류와 가격 출력하기 (Drink, DrinkMain)
1
2
3
4
5
6
7
8
9
10
11
12
13
package day05_object;
public class DrinkMain {
     
     public static void main(String[] args) {
          Drink coffee=new Drink("커피"5003);
          coffee.getData(); //커피 500 3 1500
          
          Drink tea=new Drink("녹차"8005);
          tea.getData(); //녹차 800 5 4000
          //판매금액
          System.out.println("판매금액: "+(coffee.getTotal()+tea.getTotal()));
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day05_object;
public class Drink {
     String menu;
     int price;
     int quantity;
     
     public Drink(String menu, int price, int quantity) {
          this.menu=menu;
          this.price=price;
          this.quantity=quantity;
     }
     
     public void getData() {
          System.out.print(menu+"\t");
          System.out.print(price+"\t");
          System.out.print(quantity+"\t");
          //System.out.print(price*quantity+"\n");
          System.out.println(getTotal()+"\n"); //판매금액
     }
}

 

 

+배열안에 객체 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day05_object;
public class DrinkTeaMain {
     
     
     public static void main(String[] args) {
          Drink[]arr=new Drink[100];
          //커피         500 3 1500
          //녹차         800 5 4000
          //카페라떼     1500 5 7500
     
          arr[0]=new Drink("커피"5003); //배열안에 객체 만들기
          arr[1]=new Drink("녹차"8005);
          arr[2]=new Drink("카페라떼"15005);
          
          //총판매액 출력
          
          int sum=0;
          
          for(int i=0;i<arr.length;i++) {
              if(arr[i]==nullbreak;
              arr[i].getData();
              sum+=arr[i].getTotal();
          }System.out.println("총판매액: "+sum);
          
          
     }
}
cs

 


  • 성적입력 메뉴를 메소드로 만들고 이차원배열로 성적 입력, 출력, 총점으로 석차구하기 (TwoArrayScore)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package day05_object;
import java.util.Scanner;
public class TwoArrayScore {
     static Scanner sc=new Scanner(System.in);
     int[][] arr=new int[50][7]; //50개의 행과 7개의 열(학번, 국, 영, 수, 총점, 평균, 석차)을 가진 이차원 배열 선언
     //입력되는 성적들이 다른 값들로 대체되어 지워지지 않게 배열에다가 저장해둠.
     int row=0;
     
     public void showMenu() {
          System.out.println("선택하세요");
          System.out.println("1.데이터입력");
          System.out.println("2.전체보기/종료");
          System.out.println("선택>>");
     }
     
     public void inputData() { //성적입력
          System.out.println("성적입력 시작>>");
          System.out.print("학번>>");
          int yearNum=sc.nextInt();
          System.out.print("국어>>");
          int kor=sc.nextInt();
          System.out.print("영어>>");
          int eng=sc.nextInt();
          System.out.print("수학>>");
          int math=sc.nextInt();
          arr[row][0]=yearNum;         //학번
          arr[row][1]=kor;             //국어성적
          arr[row][2]=eng;             //영어성적
          arr[row][3]=math;       //수학성적
          arr[row][4]=kor+eng+math; //총점
          arr[row][5]=arr[0][4]/3;  //평균
          arr[row][6]=1;               //석차
          row++;
     
     }
     
     public void viewData() { //전체보기
          System.out.println("------성적 보기------");
          System.out.print("학번\t국어\t수학\t영어\t총점\t평균\t순위");
          System.out.println();
          for(int i=0;i<row;i++) {
              for(int j=0;j<arr[i].length;j++) { //arr각 방에 들어있는 길이. 과목이 추가될 수도 있으니..
                   System.out.print(arr[i][j]+"\t");
              }System.out.println();
          }
     }
     
     public static void main(String[] args) {
          TwoArrayScore manager=new TwoArrayScore();
          while(true) {
              manager.showMenu(); //메뉴보여주기
              int num=sc.nextInt(); //메뉴 선택
              switch(num) {
              case 1 : manager.inputData(); break//성적입력
              case 2 : manager.viewData(); System.exit(0); //전체보기/ 종료
              default : System.out.println("입력오류");
              }
              
          }
     }
}

+석차를 어떻게 구할것인가??

1
2
3
4
5
6
7
8
9
10
11
public void rankMethod() { //석차 구하는 메소드
          for(int i=0;i<row-1;i++) {
              for(int j=i+1;j<row;j++) {
                   if(arr[i][4]>arr[j][4]) {
                        arr[j][6]++;
                   }else {
                        arr[i][6]++;
                   }
              }
          }
     }    

  • 배열을 이용하여 반지름이 1,2,3,4,5인 5개의 CircleBean객체를 만들고 각 넓이와 총 면적을 구하시오 (CircleBean, CircleBeanMain)
1
2
3
4
5
6
7
8
9
10
11
12
package day05_object;
public class CircleBean {
     int r;
     final double PI=3.14//final이 앞에 붙으면 상수
     
     public CircleBean(int r) {
          this.r=r;
     }
     public double getArea() {
          return r*r*PI;
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day05_object;
public class CircleBeanMain {
     public static void main(String[] args) {
          //반지름이 1,2,3,4,5 인 5개의 CircleBean객체를 만들고
          //각 CircleBean의 넓이를 출력하고
          //총 면적을 출력하시오
          //배열로 구하시오
          
          //배열은 선언, 생성, 초기화가 되어야함. 그 안에 값이 들어있어야 함.
          CircleBean[]arr=new CircleBean[5]; //선언&생성
          for(int i=0;i<arr.length;i++) {
              arr[i]=new CircleBean(i+1); //초기화. new해서 CircleBean이 각 방마다 만들어졌단 얘기. 1,2,3,4,5값을 가짐
          }
          double hap=0;
          for(int i=0;i<arr.length;i++) {
              System.out.println(arr[i].getArea());
              hap+=arr[i].getArea();
          }
          System.out.println("총 면적: "+hap);
     }
}

 


  • 성적입력 메뉴 클래스, 성적 입력 클래스, 출력 클래스와 총점으로 석차구하기 (Teacher, StudentBean, ScoreMain)
  • TwoArrayScore을 3개의 클래스로 나눈 것. 2차원 배열의 행들을 한 덩어리로 묶어서 1차원배열의 값으로 생각.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package day05_object;
import java.util.Scanner;
public class Teacher {
     Scanner sc=new Scanner(System.in);
     StudentBean[] arr=new StudentBean[50];
     int cnt; //멤버변수의 int는 초기값이 0이다.
     
     public void showMenu() {
          System.out.println("선택하세요");
          System.out.println("1.데이터입력");
          System.out.println("2.전체보기");
          System.out.println("3.종료");
          System.out.println("선택>>");
     }
     
     public void inputData() {
          System.out.println("성적입력 시작>>");
          System.out.print("이름>>");
          String name=ScoreMain.sc.next();
          System.out.print("국어>>");
          int kor=ScoreMain.sc.nextInt();
          System.out.print("영어>>");
          int eng=ScoreMain.sc.nextInt();
          System.out.print("수학>>");
          int math=ScoreMain.sc.nextInt();
          //배열에 StudentBean 객체 넣기
          arr[cnt] = new StudentBean(name, kor, eng, math);
          cnt++;
     }
      public void rankMethod() { //석차 구하는 메소드
          for(int i=0;i<cnt-1;i++) {
              for(int j=i+1;j<cnt;j++) {
                   if(arr[i].getTotal()>arr[j].getTotal()) {
                        arr[j].setRank(1); //arr[j]의 rank에 1을 더한다.
                   }else if(arr[i].getTotal()<arr[j].getTotal()) {
                        arr[i].setRank(1); //arr[i]의 rank에 1을 더한다.
                   }
              }
          }
     }
     
     public void viewData() {
          rankMethod();
int sum=0; //지역변수는 반드시 초기값이 필요.
          System.out.println("-----학생 성적 보기------");
          System.out.println("이름\t총점\t평균\t석차");
          for(int i=0;i<cnt;i++) {
              System.out.print(arr[i].name+"\t");
              System.out.print(arr[i].getTotal()+"\t");
              System.out.print(arr[i].getAvg()+"\t");
              System.out.print(arr[i].rank+"\n");
              }
          System.out.println("학급 총점: "+sum);
System.out.println("학급 평균: "+sum/cnt);
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day05_object;
public class StudentBean {
     String name;
     int kor, eng, math;
     int rank=1;
     
     public StudentBean(String name, int kor, int eng, int math) {
          this.name=name;
          this.kor=kor;
          this.eng=eng;
          this.math=math;
     }
     
     public int getTotal() {
          return kor+eng+math;
     }
     
     public double getAvg() {
          return getTotal()/3;
     }
     
     public void setRank(int rank) {
          this.rank+=rank;
     }
     
     
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day05_object;
import java.util.Scanner;
public class ScoreMain {
     static Scanner sc=new Scanner(System.in);
     
     public static void main(String[] args) {
          Teacher t1=new Teacher();
          while(true) {
              t1.showMenu();
              int num=sc.nextInt();
              switch(num) {
              case 1 : t1.inputData(); break;
              case 2 : t1.viewData(); break;
              case 3 : System.out.println("종료");
                             System.exit(0);
              default : System.out.println("입력오류");
              }
          }
          
     }
}