본문 바로가기

Learning/JAVA

이차원배열, ArrayList활용, 자바의 상속성

  • 이차원배열의 인덱스 값을 일차원배열로 지정, 출력 순서를 행 단위로 바꾸기 (ShiftArray)
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
package day06_objectArray;
public class ShiftArray {
     
     public static void shiftArray(int [][]arr) {
          //일차원 배열을 만들고 그 배열에 arr의 마지막 행 값을 넣는다.
          int []tmp=arr[arr.length-1];
          //arr의 인덱스가 2에 1의 값을 넣는다.
          //arr의 인덱스가 1에 0의 값을 넣는다.       
          for(int i=arr.length-2;i>=0;i--) {
                   arr[i+1]=arr[i];
              }
          //arr의 인덱스가 0의 위치에 처음 만든 일차원 배열을 넣는다.
          arr[0]=tmp;
     }
     
     public static void showArray(int [][]arr) {
          for(int i=0;i<arr.length;i++) {
              for(int j=0;j<arr[i].length;j++) {
                   System.out.print(arr[i][j]+"\t");
              }System.out.println();
          }
     }
     
     
     public static void main(String[] args) {
          int [][]arr= {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
          
          System.out.println("1차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          System.out.println("2차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          /*
           * 1차 shift...
           * 7 8 9
           * 1 2 3
           * 4 5 6
           * 2차 shift...
           * 4 5 6
           * 7 8 9
          */
     }
}

 


  • ArrayList활용. 학생의 학번, 이름, 과목 성적 입력하고 출력하기 (StudentTest, Student, Subject)
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
package day06_objectArray.arraylist;
//import java.util.ArrayList;
public class Student {
     int studentID;
     String studentName;
     Subject []subjectList;
     int index;
     //ArrayList<Subject>subjectList;
     
     public Student(int studentID, String studentName) {
          this.studentID=studentID;
          this.studentName=studentName;
          subjectList=new Subject[10];
          //subjectList=new ArrayList<Subject>();
     }
     //배열을 대신해서 사용할 수 있는게 ArrayList.
     //학생이 여러 과목을 듣는데 그걸 따로 과목에 대한 클래스로 따로 분류
     //그걸 배열에 담음.
     //배열은 처음에 공간을 정해줘야함. 대신에 ArrayList는 추가한만큼 크기가 변화함
     //ArrayList는 함수를 이용해서 접근.
     
     public void addSubject(String name, int score) {
          Subject subject=new Subject();
          subject.setName(name);
          subject.setScorePoint(score);
          subjectList[index++]=subject;
          //subjectList.add(subject);
     }
     
     public void showStudentInfo() {
          int total=0;
          for(Subject s : subjectList) {
              if(s==nullbreak;
              total+=s.getScorePoint();
              System.out.println("학생 "+studentName+"의 "+s.getName()+"과목 성적은 "+s.getScorePoint()+"입니다.");
          }
          System.out.println("학생 "+studentName+"의 총점은 "+total+" 입니다.");
     }
}

 


  • 학생클래스, 버스, 지하철, 택시 클래스를 구현하여 학생이 버스나 지하철을 타고 요금을 냈을때 학생이름, 잔액, 버스 승객, 버스 수입, 지하철 승객, 지하철 수입을 출력하기 (Student, Bus, Subway, Taxi, TakeTrans)
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
package cooperation;
 
public class TakeTrans {
    
    public static void main(String[] args) {
        Student s1=new Student("홍길동"5000);
        Student s2=new Student("이순신"10000);
        Student s3=new Student("Edward"20000);
        
        Bus bus=new Bus(100); //100번 버스
        //s1학생이 100번 버스를 탄다.
        s1.takeBus(bus); //매개변수가 객체가 됨.
        
        Subway subway=new Subway("2호선");
        //s2학생이 2호선 지하철을 딴다.
        s2.takeSubway(subway);
        
        Taxi taxi=new Taxi("yellow");
        s3.takeTaxi(taxi);
        
        s1.showInfo();
        s2.showInfo();
        s3.showInfo();
        
        bus.showInfo();
        subway.showInfo();
        taxi.showInfo();
        
    }
}

 

 

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
package cooperation;
 
public class Student { 
    private String studentName; //학생이름
    private int grade; //학년
    private int money; //학생이 가지고 있는 돈
    
    public Student(String studentName, int money) {
        this.studentName=studentName;
        this.money=money;
    }
    
    //버스타다
    public void takeBus(Bus bus) { //Bus형에 bus가 들어감. 매개변수를 객체로.
        bus.take(1000);
        this.money-=1000;
    }
    
    //지하철타다
    public void takeSubway(Subway subway) { //Subway형에 subway가 들어감.
        subway.take(1500);
        this.money-=1500;
    }
    
    public void takeTaxi(Taxi taxi) {
        taxi.take(10000);
        this.money-=10000;
    }
    
    public void showInfo() {
        System.out.println("학생 이름: "+studentName);
        System.out.println("학생 잔액: "+money);
    }
    
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cooperation;
 
public class Subway {
    private String subwayNumber; //지하철번호
    private int passengerCount; //승객수
    private int money; //수입
    
    public Subway (String subwayNumber) {
        this.subwayNumber=subwayNumber;
    }
    
    //승객이 돈을 내고 탑승
    public void take(int money) {
        this.money+=money; //수입증가
        passengerCount++//승객 수 증가
    }
    
    public void showInfo() {
        System.out.println("지하철 "+subwayNumber);
        System.out.println("승객 "+passengerCount);
        System.out.println("수입 "+money);
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cooperation;
 
public class Taxi {
    private String taxiColor;
    private int money;
    private int passengerCount;
    
    public Taxi(String taxiColor) {
        this.taxiColor=taxiColor;
    }
    
    public void take(int money) {
        this.money+=money;
        passengerCount++;
    }
    
    public void showInfo() {
        System.out.println("택시 "+taxiColor);
        System.out.println("승객 "+passengerCount);
        System.out.println("수입 "+money);
    }    
}

 


  • 자바의 상속성 (Child, Father, GrandFather, Main)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package day07;
public class Main {
     public static void main(String[] args) {
          Father f1=new Father();
//        f1.fatherPrint();
          
          Child c1=new Child();
//        c1.childPrint();
          
//        f1.methodTest();
          //c1.test();
//        c1.methodTest();
          GrandFather g1=new GrandFather();
          c1.grandPrint();
          f1.grandPrint();
          
     }    
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day07;
public class Child extends Father { //Child는 Father걸 다 쓸 수 있다. 상속받는다.
     //이미 만들어져 있는걸 갖다 쓸 수 있기 때문에 중복을 최소화 할 수 있다. 코드가 간략해짐.
     //상속 받았기 때문에 무조건 생성자를 먼저 수행하고 자신의 메소드를 수행
     //자바에서 다중상속은 안되고 단일상속만 된다.
     public Child() {
//        super("부모를 호출"); //super();는 부모의 생성자를 부르는 말. 생략 가능하다.
          //super(인자);
          System.out.println("자식 생성자");
     }
     
     public void childPrint() {
          System.out.println(super.str); //this가 자기 자신의 객체를 불렀던 것처럼, 괄호 없는 super는 부모의 객체를 부른다.
          System.out.println("child print 메소드");
     }
     
     public void test() {
          System.out.println("test method");
     }
}

 

 

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
package day07;
public class Father extends GrandFather {
     String str="아버지"//멤버변수
     
     public Father() {
          System.out.println(str+" 생성자 ");
     }
     
     public Father(String msg) {
          System.out.println(msg);
     }
     
     public void fatherPrint() {
          System.out.println("father print 메소드");
     }
     
     public void methodTest() {
          System.out.println("test method");
     }
     
     //오버라이드. (메소드 오버라이딩) 상속관계에 있어서 부모의 것을 자식이 재정의 하는 것.
     //(오버로딩: 메소드나 생성자 이름은 같은데 괄호안에 들어있는 매개변수가 달라서 다르게 접근하는 것)
     public void grandPrint() { //할아버지 메소드. 오버라이딩 됨. 할아버지가 아니라 아버지에 있는 것이 출력됨.
          System.out.println("할아버지 grandPrint 메소드를 father가 수정함");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
package day07;
public class GrandFather {
     String name="할아버지";
     //생성자
     public GrandFather() {
          System.out.println(name+" 생성자");
     }
     
     public void grandPrint() {
          System.out.println("grandPrint 메소드");
     }
}

 


  • 자바의 상속성-부모의 생성자를 못찾을때 디폴트 생성자 만들어주기, 부모의 인자를 부를때 super 사용. (PointMain, Point)
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
package day07;
public class PointMain extends Point {
     private String color;
     public PointMain (int x, int y, String color) {
          super(x,y); //x,y가 있는 부모의 생성자를 불러준다.
          this.color=color;
     }
     //색깔도 출력시키고 싶다면 좌표만 출력시키는 부모의 disp()메소드를 오버라이딩 해주면 된다.
     //부모의 인자값 출력하려면 super를 붙이면 됨.
     @Override //어노테이션. 컴파일 할때 알려줌. 이름이 달라지면 오류발생. 오버라이드가 아니게 되므로.
     public void disp() {
          // TODO Auto-generated method stub
          super.disp();
          System.out.println("Color: "+color);
     }
     public static void main(String[] args) {
          PointMain pm=new PointMain(5,5,"Yellow");
          pm.disp();
          pm.move(10,20);
          pm.disp();    
          
          System.out.println(pm.str);
          
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package day07;
public class Point {
     private int x;
     private int y;
     protected String str="Point"//protected는 상속관계의 접근제어자.
     
     //인자없는 생성자를 만들어준 것. 껍데기
     Point(){}
     
     public Point(int x, int y) {
          this.x=x;
          this.y=y;
     }
     
     public void disp() {
          System.out.println("점(x,y)=("+x+","+y+")");
     }
     
     public void move(int x, int y) {
          this.x=x;
          this.y=y;
     }
}

 


  • 자바의 상속성-오버라이드를 통해 TV의 스펙 출력하기 (TVMain, TV, ColorTV, IPTV)
1
2
3
4
5
6
7
8
9
10
11
12
package day07;
//32인치 1024컬러
//나의 IPTV는 192.1.1.2 주소의 32인치 2048컬러
public class TVMain {
     public static void main(String[] args) {
          ColorTV myTV=new ColorTV(32,1024);
          myTV.printProperty();
          
          IPTV iptv=new IPTV("192.1.1.2",32,2048);
          iptv.printProperty();
     }
}

 

 

1
2
3
4
5
6
7
package day07;
public class TV {
     protected int inch;
     public TV(int inch) {
          this.inch=inch;
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package day07;
public class ColorTV extends TV {
     protected int nColors;
     
     public ColorTV(int inch, int nColors) {
          super(inch);
          this.nColors=nColors;
     }
     
     public void printProperty() {
          System.out.println(inch+"인치 "+nColors+"컬러");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package day07;
public class IPTV extends ColorTV {
     private String address;
     
     public IPTV(String address, int inch, int nColors) {
          super(inch,nColors); //super로 가져오는 인자들은 항상 맨 윗줄에 써야함.
          this.address=address;
     }
     
     public void printProperty() {
          System.out.println("나의 IPTV는 "+this.address+" 주소의 "+inch+"인치 "+nColors+"컬러");
          super.printProperty();
     }
}

 


  • 자바의 상속성-메뉴 입력하여 원, 사각형 등의 도형 스펙 출력하기 (ShapeMain, Shape, Circle, Square, ShapeManager)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package day07;
 
public class Shape {
    private int x;
    private int y;
    
    public Shape(int x, int y) {
        this.x=x;
        this.y=y;
    }
    
    public void print() {
        System.out.println("좌표(x,y)=("+x+","+y+")");
    }
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package day07;
 
public class Circle extends Shape {
    private int r;
    
    public Circle(int x, int y, int r) {
        super(x,y);
        this.r=r;
    }
    //오버라이딩
    public void print() {
        super.print();
        System.out.println("반지름: "+r);
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package day07;
 
public class Square extends Shape {
    private int w,h;
    
    public Square(int x, int y, int w, int h) {
        super(x,y);
        this.w=w;
        this.h=h;
    }
    
    public void print() {
        super.print();
        System.out.println("너비: "+w);
        System.out.println("높이: "+h);
    }
}

 

 

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
package day07;
 
import java.util.Scanner;
 
public class ShapeMain {
    static Scanner sc=new Scanner(System.in);
    
    public static void showMenu() {
        System.out.println("선택하세요...");
        System.out.println("1.원 2.사각형 3.보기 4.종료");
        System.out.print("선택:");
    }
    
    public static void main(String[] args) {
            ShapeManager sm=new ShapeManager();
            
            while(true) {
            ShapeMain.showMenu(); 
            //클래스 이름에 static 불였으니까 ShapeMain으로 부를 수 있음.
            int num=sc.nextInt();
            switch(num) {
            case 1 : //원입력
            case 2 : sm.inputData(num); break//사각형입력
            case 3 : sm.viewData(); break//전체보기
            case 4 : System.out.println("종료");
                     System.exit(0);
            default : System.out.println("입력오류");
            }
        }
    }
}
 

 

 

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
package day07;
 
public class ShapeManager {
    //입력받은 좌표, 반지름, 너비, 높이 등을 저장하기 위해 배열 선언
    //부모형으로 선언을 해야 Circle, Square 모두 적용가능
    Shape[]arr=new Shape[50]; 
    int cnt;
    
    public void inputData(int num) { //원->x,y,r 사각형->x,y,w,h
        System.out.println("도형입력....");
        System.out.print("x 좌표>>");
        int x=ShapeMain.sc.nextInt();
        System.out.print("y 좌표>>");
        int y=ShapeMain.sc.nextInt();
        
        if(num==1) { //원
            System.out.print("반지름>>");
            int r=ShapeMain.sc.nextInt();
            arr[cnt++]=new Circle(x,y,r);
        }
        else if(num==2) { //사각형
            System.out.print("너비>>");
            int w=ShapeMain.sc.nextInt();
            System.out.print("높이>>");
            int h=ShapeMain.sc.nextInt();
            arr[cnt++]=new Square(x,y,w,h);
        }
    }
    
    public void viewData() {
        for(Shape s: arr) {
            if(s==nullbreak;
            s.print();
        }
    }
}