문준영
새벽 코딩
문준영
전체 방문자
오늘
어제
  • 분류 전체보기
    • 웹 개발
    • JAVA
      • 기본 문법 내용 정리
      • 함수 내용 정리
      • 쉽게 배우는 자바 프로그래밍 문제 풀이
    • HTML
      • HTML
      • CSS
      • 문제풀이
    • JavaScript
    • MYSQL
    • C
      • 기본 문법 내용 정리
      • 백준 알고리즘 (c언어)
      • 자료구조
    • Python
      • 참고 알고리즘
      • 기본 문법 내용 정리
      • 자료구조 내용 정리
      • 백준 알고리즘 (파이썬)
    • 깃허브
    • 멀티잇 풀스택

티스토리

hELLO · Designed By 정상우.
문준영

새벽 코딩

쉽게 배우는 자바 프로그래밍 문제 풀이 2장 ~7장
JAVA/쉽게 배우는 자바 프로그래밍 문제 풀이

쉽게 배우는 자바 프로그래밍 문제 풀이 2장 ~7장

2021. 10. 8. 11:27

 

2장

2.1 println() 메서드를 이용해 다음 형태의 피라미드를 출력하는 프로그램을 작성하시오.

 

4

             *

            ***

           *****

          *******

         *********

        ***********

정답

for(int i=0;i<=10;i+=2) {
            for(int k=0;k<=10-i;k+=2) {
                System.out.print(" ");
            }
            for(int j=0;j<=i;j++) {
                System.out.print("*");
            }
        
            System.out.println();
        }

 

 


2.4 초를 입력하면 시간, 분, 초로 환산해 출력하는 프로그램을 작성하시오.

정답 

  int min=0,hour=0,sec,time=0;
        Scanner sc =new Scanner(System.in);
        System.out.print("초 입력 :");
        sec=sc.nextInt();
        
        min=sec/60;
        hour=min/60;
        min=min%60;
        sec=sec%60;
        System.out.printf("-> %d시간 %d분 %d초 ",hour,min,sec)

2.5 임의의 소문자로 초기화된 char 타입 변수 c를 대문자로 변환해 출력하는 프로그램을 작성하시오

정답 

Scanner sc =new Scanner(System.in);
System.out.print("소문자 입력:");
char input=sc.next().charAt(0);
int input2= (int)input;
System.out.println("대문자 출력:"+(char)(input2-32);

*Scanner는 무조건 String으로 받아온다. 그래서 chatAt(0)을 통해 한글자를 char 형태로 반환한다.

대소문자 아스키 코드의 차이는 32이다. -32를 써도 좋고 (int)'A'-(int)'a'를 통해서 -32를 구해도 좋다.


2.6 키보드로 화씨온도(F)를 입력받아 섭씨온도(C)로 환산해 출력하는 프로그램을 작성하시오.

  • 화씨온도 F를 섭씨온도 C로 바꾸는 수식 : C = (5*(F - 32)) / 9
  • 정수 타입을 사용하면 5/9는 0이 되므로 정확한 결과를 얻을 수 없다.

정답 

Scanner sc =new Scanner(System.in);
System.out.print("화씨(F):");
double F=sc.nextInt();
System.out.printf("섭씨(C):%.1f",((5*(F-32))/9));

2.7 키보드로 정수를 입력받아

  1. 4와 5로 나누어지는지
  2. 4 또는 5로 나누어지는지
  3. 4나 5 중 하나로 나누어지지만 두 수 모두로는 나누어지지 않는지를 true/false로 출력하는 프로그램을 작성하시오

정답 

Scanner sc =new Scanner(System.in);
int input=sc.nextInt();
System.out.println(input%4==0 &&input%5==0 ? "true" : "false");
System.out.println(input%4==0 ||input%5==0 ? "true" : "false");
System.out.println((input%4==0 ||input%5==0)&&(input%4!=0 &&input%5!=0) ? "true" : "false");

 



2.8  키보드로 0부터 999 사이의 정수를 입력받아 각 자릿수를 더한 결과를 출력하는 프로그램을 작성하시오.

0 ~ 999 사이의 숫자를 입력하세요 : 194
각 자릿수의 합 = 14

 

정답

Scanner sc= new Scanner(System.in);
String a ;
System.out.print("0~999 사이의 숫자를 입력하세요: ");
a=sc.next();
int sum=0;
for(int i=0;i<a.length();i++) {
 sum+=Integer.parseInt(a.substring(i,i+1));
 }
 System.out.println("각 자릿수의 합="+sum);

 

배열로 받을라고 했지만 방법이 없음 결국에는 문자형으로 받아와 한자리씩 끊어서 정수로 형변환을 해야 한다.

*문자형 -> 정수형 : Integer.parseInt(String)

*String.substring(a) : 입력한 인덱스 a 부터 끝까지 반환

 String.substring(a,b) : 인덱스 번호 a ~ (인덱스번호 b -1)까지 반환 

 

 

3장 

 

3.5 각 변의 길이 합이 20 이하이며 각 변의 길이가 정수인 직각 삼각형의 모든 변을 구하시오.

※ 피타고라스 정리, 즉 a^2 + b^2 = c^2을 이용하고 for문을 중첩해서 사용한다.

정답

for(int a=1;a<=20;a++) {
   for(int b=1;b<=20;b++) {
       for(int c=1;c<=20;c++) {
           if(a+b+c<=20 &&Math.pow(a,2)+Math.pow(b,2)==Math.pow(c, 2)) {
              System.out.printf("변:a:%d b:%d c:%d \n",a,b,c);
                  }}}}
 

 

제곱근 : math.pow(수,제곱근수)


3.6 철수와 영희가 가위(s), 바위(r), 보(p) 게임을 한다. 다음 실행 결과와 같이 r, p, s 중 하나를 입력해 승자 또는 무승부를 출력하는 프로그램을 작성하시오.

철수 : r
영희 : s
철수, 승!

정답

public void rps(char a,char b){
        if(a==b) {
            System.out.println("무승부");
        }else if(a=='r' && b=='s' || a=='s'&&b=='p'||a=='p'&&b=='r') {
            System.out.println("철수 승리");
        }else {
            System.out.println("영희 승리");
        }
        
        
    }
    
    
    
public static void main(String[] args) {
        
       Scanner sc=new Scanner(System.in);
       Pra p=new Pra();
       System.out.print("철수:");
       char input1=sc.next().charAt(0);
       System.out.print("영희:");
       char input2=sc.next().charAt(0);
    
       p.rps(input1, input2);
 

String으로 한 문자를 받으면 반드시 char로 변환해주어야함

 

 

 

4장

 

4.1 삼각형을 나타내는 Triangle 클래스를 작성하시오. 삼각형의 속성으로는 실수 값의 밑변과 높이를, 동작으로는 넓이 구하기와 접근자가 있고 생성자도 포함된다. 작성한 클래스를 다음 코드를 사용해 테스트하시오.

 

public class TriangleTest {
    public static void main(String[] args) {
        Triangle t = new Triangle (10.0, 5.0);
        System.out.println(t.findArea());
    }
}

정답

public class Pra {
    double a;
    double b;
    public Pra(double a,double b){ //생성자
        this.a=a;
        this.b=b;
    }
    public double get_a() { //접근자
        return a;
    }
    public double get_b() { //접근자
        return b;
    }
    public double findArea() { //넓이 메소드
        
        return a*b/2;
    }
    
    public static void main(String[] args) {
        
        Pra p=new Pra(10.0,5.0);
        System.out.println(p.findArea());
 

   생성자 : 초기 값 지정 -> class_name (매개변수1,매개변수 2..){

                                         this.매개변수1=매개변수1; this.매개변수2=매개변수2;  .. }

   설정자 : 필드 변경   -> void set메소드(매개변수) { this.매개변수=매개변수; }

   접근자: 변경된 필드 읽기 ->반환형 get메소드() { return 매개변수 } 


4.2  4장 1번에서 작성한 Triangle 클래스에 2개의 삼각형 넓이가 동일한지 비교하는 isSameArea() 메서드를 추가하시오. 그리고 다음 코드를 사용해 테스트하시오.

 

public class TriangleTest {
    public static void main(String[] args) {
        Triangle t1 = new Triangle (10.0, 5.0);
        Triangle t2 = new Triangle (5.0, 10.0);
        Triangle t3 = new Triangle (8.0, 8.0);


        System.out.println(t1.isSameArea(t2));
        System.out.println(t1.isSameArea(t3));
    }
}

정답

public boolean isSameArea(Pra pp) {
    if(pp.findArea()==this.findArea()) return true;
    else return false;
        
    }
 

다른 객체메소드와 비교할 때는 매개변수안에 객체를 넣어주고

객체변수를 적용한 메소드와 현재 메소드를 비교하면 된다.


4.3 회원을 관리하려고 회원을 모델링한 Member 클래스를 작성하시오. 회원 정보로는 이름, 아이디, 암호, 나이가 있다. 외부 객체는 이와 같은 회원 정보에 직접 접근할 수 없고 접근자와 설정자로만 접근할 수 있다. 그리고 모든 회원 정보를 사용해 객체를 생성할 수 있는 생성자도 있다.

정답

class Member{
    private int age,id,password;
    private String name;
    public Member(int age,String name,int id, int password) {
        this.age=age;
        this.name=name;
        this.id=id;
        this.password=password;
        }
    public void Set_member(int age,String name,int id, int password) {
        this.age=age;
        this.name=name;
        this.id=id;
        this.password=password;
        }
    
    public int get_age() {
        return age;
    }
    public String get_name() {
        return name;
    }
    public int get_id() {
        return id;
    }
    public int get_password() {
        return password;
    }
}
 

 


4.4 생산된 모든 자동차와 빨간색 자동차의 개수를 출력하는 Car 클래스를 작성하시오. 그리고 다음 코드를 사용해 테스트하시오.

public class CarTest {
    public static void main(String[] args) {
        Car c1 = new Car("red");
        Car c2 = new Car("blue");
        Car c3 = new Car("RED");

        System.out.printf("자동차 수 : %d, 빨간색 자동차 수 : %d",Car.getNumOfCar(),Car.getNumOfRedCar());
    }
}

정답

class Car{
    String color;
    static int car_num=0;
    static int redcar_num=0;

    Car(String color){
        this.color=color;
        car_num++;
        if (color=="red") redcar_num++;
    }
    static int getNumOfCar() {
        return car_num;
    }
    static int getNumOfRedCar() {
        return redcar_num;
    }
    
}
 

정적 변수 사용하여 변수 값 공유


4.5 길이 속성만 가진 직선을 모델링한 Line 클래스를 작성하고, 다음 프로그램으로 테스트하시오.

 

public class LineTest {
    public static void main(String[] args) {
        Line a = new Line(1);
        Line b = new Line(1);

        System.out.println(a.isSameLine(b));
        System.out.println(a == b);
    }
}
true
false

정답

public class Line{    
    int num;
    Line(int num){
        this.num=num;
    }
    public int get_num() {
        return num;
    }
    public boolean isSameLine(Line num) {
        if(get_num() ==num.num) {
            return true;
        }
        else {
            return false;
        }
    }

 

 == : 객체 비교 ( 클래스를 이용한 객체 생성 시 각각 객체가 아닌 다른 레퍼런스를 얻음) : false

a.equlas(b) : 단순 값 비교


4.6 복소수를 모델링한 Complex 클래스를 작성하고, 다음 프로그램으로 테스트하시오.

public class ComplexTest {
    public static void main(String[] args) {
        Complex c1 = new Complex(2.0);
        c1.print();
        Complex c2 = new Complex(1.5, 2.5);
        c2.print();
    }
}
2.0 + 0.0i
1.5 + 2.5i

정답

class Complex{
    private double l;
    private double l2;
    Complex(double l){
        this.l=l;
    }
    Complex(double l, double l2){
        this.l=l;
        this.l2=l2;
    }
    public void print() {
        System.out.println(l+" + "+l2+"i");
    }
    
    
}
 

 생성자 오버로딩

 

 


4.8 주사위를 나타내는 Dice 클래스를 작성하고, 다음 코드를 사용해 테스트하시오.

Dice 클래스에는 6개의 면(face)이라는 속성과 굴리기(roll)라는 동작이 있다. Math.random() 메서드는 0.0 이상 1.0 미만의 double 타입의 무작위 실수를 반환한다.

 

public class DiceTest {
    public static void main(String[] args) {
        Dice d = new Dice();
        System.out.println("주사위의 숫자 : " + d.roll());
    }
}

정답

class Dice{
    int rand;
    public Dice() {
        this.rand=rand;
    }
    public int roll() {
        rand=(int)(Math.random()*6+1);
        return rand;
    }
    
}
 

(반복할 수)+ first 값

-> (last 값 - first 값 +1 ) + first 값   ex) 5~12  -> (int)(math.random()*8+5)

5장

5.2  다음 코드를 실행하면 9, 5, 14를 두 번 출력한다. 여기서 sum() 메서드를 하나로 완성하시오.

자바는 가변 길이 변수를 배열처럼 취급한다.

 

public static void main(String[] args) {
        System.out.println(sum(1,2,3,4));
        int arr[] = {2,3};
        System.out.println(sum(1,arr));
        System.out.println(sum(1,2,3,4,5));
    }

정답

public static int sum(int number,int ...number2) {
        int num=0;
        for(int i=0;i<number2.length;i++) {
            num+=number2[i];
        }
        return num;
    }
 

1. 정적 메서드를 사용해야 없이 객체없이 메소드를 실행 할 수있다. (정적 메소드는 정적 변수만 사용가능)

2. sum 메서드에서 첫번 째 값은 무시한다. 그 이후 뒤 매개변수가 몇개가 올지 모르니 (자료형 ... 변수)를

    사용하여 임의의 매개변수를 설정한다. 

 


5.3  [예제 5-6]은 3년간 분기별 이자율에 대한 연평균 이자율과 평균 이자율을 출력하는 예제이다. 이를 for~each 문을 사용해 작성하시오.

 

[예제 5-6]

public class Array2Demo {
    public static void main(String[] args) {
        double[][] interests = {{3.2, 3.1, 3.2, 3.0}, {2.9, 2.8, 2.7, 2.6}, {2.7, 2.6, 2.5, 2.7}};
        double[] sum1 = {0.0, 0.0, 0.0};
        double sum2 = 0.0;

        for (int i=0; i< interests.length;i++) {
            for (int j=0; j<interests[i].length; j++) {
                sum1[i] += interests[i][j];
            }

            System.out.printf("%d차년도 평균 이자율 = %.2f%%\n", i+1, sum1[i]/4);
            sum2 += sum1[i];
        }
        System.out.printf("3년간 평균 이자율 = %.2f%%\n",sum2/3);
    }
}

[예제 5-6 실행 결과]

정답 

int year=1;
        for(double[] i:interests) {
            double sum=0;
            
            for(double j:i) {
                sum+=j;
                sum2+=j;
            }System.out.printf("%d차년도 평균 이자율=%.2f%%\n",year,sum/4);
             year+=1;
        
        }
        System.out.printf("3년간 평균 이자율=%.2f%%\n",sum2/3);

 

 


5.4  다음과 같이 키보드에서 URL을 입력받은 후 'com'으로 끝나는지, 'java'를 포함하는지 조사하는 프로그램을 작성하시오. 'bye'를 입력하면 프로그램은 종료된다.

URL을 입력하세요 : www.java.com
www.java.com은 'com'으로 끝납니다.
www.java.com은 'java'를 포함합니다.


URL을 입력하세요 : bye
 
 

정답

Scanner sc=new Scanner(System.in);
        String input;
        
     do {
        System.out.print("URL을 입력하세요 :");
        input=sc.nextLine();
        if(input.endsWith("com")){
        System.out.printf("%s은 com으로 끝남\n",input);
        }
        if(input.contains("java")) {
            System.out.printf("%s은 java 포함합니다.\n",input);
        }
     }while(!input.equals("bye"));
 

문자를 비교하려면 a.equals(b) 를 사용  ( == 는 주소 값을 비교 )

 

boolean 형태

 1. 포함 문자를 알기 위해서는 arr.contains("문자") 메서드 사용

 2. 마지막으로 끝난 문자를 알기 위해서는 arr.endsWith("문자") 사용


5.5   0~99 사이의 정수를 키보드에서 10개 입력받아 10 단위 간격의 히스토그램을 출력하는 프로그램을 작성하시오. 입력된 수가 음수이면 무시하시오. 예를 들어 위쪽처럼 10개의 정수가 입력되었을 때는 아래쪽처럼 히스토그램을 출력한다.

 

정답

Scanner sc=new Scanner(System.in);
        String r="*";
        int arr[]=new int[10];
        int arr2[]=new int[10];
        System.out.println("숫자 10개 입력하시오.");
        for(int i=0;i<arr.length;i++) {
            arr[i]=sc.nextInt();
        
            if(arr[i]<0) {
            }
            else if(arr[i]<10) {
                arr2[0]+=1;
            }else if(arr[i]<20) {
                arr2[1]+=1;
            }else if(arr[i]<30) {
                arr2[2]+=1;
            }else if(arr[i]<40) {
                arr2[3]+=1;
            }else if(arr[i]<50) {
                arr2[4]+=1;
            }else if(arr[i]<60) {
                arr2[5]+=1;
            }else if(arr[i]<70) {
                arr2[6]+=1;
            }else if(arr[i]<80) {
                arr2[7]+=1;
            }else if(arr[i]<90) {
                arr2[8]+=1;
            }else if(arr[i]<100){
                arr2[9]+=1;
            }
            
        }
        
     for(int i=0;i<arr.length;i++) {
         System.out.printf("%d ~ %d: %s\n",i*10,(i*10)+9,r.repeat(arr2[i]));
        
     }    }
    }

 


 

5.6 주어진 배열의 원소를 역순으로 변환한 배열을 반환하는 다음 메서드를 작성하시오.

public static int[] reverse(int[] org)

정답

public static int[] reverse(int [] arr) {
        int arr2[]=new int[arr.length];
        int num=0;
        for(int i=arr.length-1;i>=0;i--) {
            arr2[num]=arr[i];
            
            num+=1;
            
        }
        
        return arr2;
        
    }

 


 

5.7   2개의 1차원 배열에서 내용이 같은지를 조사하는 메서드를 정의하고, 다음 배열을 사용해 테스트하시오.

 

int[] a = {3,2,4,1,5};
int[] b = {3,2,4,1};
int[] c = {3,2,4,1,5};
int[] d = {2,7,1,8,2};

정답

 public static boolean same(int arr[],int arr2[]) {
            return Arrays.equals(arr, arr2);
    }
 

 


5.8   다음과 같은 지뢰 찾기 게임 프로그램을 작성하시오. 실행 결과는 '5 10 0.3'을 명령행 인수로 사용한 예이다.

  • 프로그램은 3개의 명령행 인수(m, n, p)를 받아들이고, m * n 크기의 배열을 생성해 지뢰를 숨긴다.
  • 숨긴 지뢰가 있는 원소는 *로 표시하고 없는 원소는 -로 표시한다. 원소에 지뢰가 있을 확률은 세 번째 명령행 인수인 p이다.
  • 지뢰 숨김 여부를 나타내는 2차원 배열을 출력하고, 지뢰를 숨기지 않은 원소를 -대신에 이웃한 지뢰 개수로 채운 2차원 배열도 함께 출력한다.
  • 이웃한 지뢰는 상하좌우 및 대각선 원소에 숨긴 지뢰를 의미한다.
  • 지뢰 숨긴 지역을 30%로 설정하려면, 난수 발생 정적 함수 Math.random() 값이 0.3보다 적은 원소에 지뢰를 숨긴다.

정답

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a,b;
        double sum;
        a=sc.nextInt();
        b=sc.nextInt();
        sum=sc.nextDouble();
        String[][] arr=new String[a][b]; //arr 설정 

        for(int i=0;i<arr.length;i++) { // 지뢰설정
            for(int j=0;j<arr[i].length;j++) {
                if(Math.random()<=sum) {
                    arr[i][j]="*";
                }
                else {
                    arr[i][j]="-";
                }}}
        
        for(int i=0;i<arr.length;i++) { //지뢰판 출력
            for(int j=0;j<arr[i].length;j++) {
                System.out.print(arr[i][j]);
            }
            System.out.println();
            }
        
        System.out.println();
        
        for(int i=0;i<arr.length;i++) { //숫자가 입력된 지뢰판 출력
            for(int j=0;j<arr[i].length;j++) {
                
                int boom=0;
                
                if(i>0) { // 상하좌우,대각선에 지뢰가 있으면 boom+1 이후 형변환을 통해 arr에 넣어줌
                if(arr[i-1][j]=="*" ) { // 인덱스 번호가 초과되면 오류가 띄기때문에 if문을 한번
                    boom+=1; // 더 둘러싸 오류를 방지한다.
                }}
                
                if(i+1<arr.length) {
                if(arr[i+1][j]=="*" ) {
                    boom+=1;
                }}
                
                if(j+1<arr[i].length) {
                if(arr[i][j+1]=="*") {
                    boom+=1;
                }}
                
                if(j>0) {
                if(arr[i][j-1]=="*") {
                    boom+=1;
                }}
                
                if(i+1<arr.length && j+1<arr[i].length) {
                if(arr[i+1][j+1]=="*") {
                    boom+=1;
                }}
                
                if(i>0 && j>0) {
                if(arr[i-1][j-1]=="*") {
                    boom+=1;
                }}
                
                if(i+1<arr.length && j>0) {
                if(arr[i+1][j-1]=="*") {
                    boom+=1;
                }}
                
                if(i>0 && j+1<arr[i].length) {
                if(arr[i-1][j+1]=="*") {
                    boom+=1;
                }}
                
                if(arr[i][j]=="-") {
                arr[i][j]=Integer.toString(boom); //형변환
                }
                
                System.out.print(arr[i][j]);
                }
                System.out.println();
                
            }
            }   }
 

 

 

6장

 

6.2   다음 표와 실행 결과를 참고해서 답하시오. show() 메서드는 객체의 정보를 문자열로 반환한다.

  Person Student ForeignStudent
필드 이름,나이 학번 국적
메서드 접근자와 생성자, show()
생성자 모든 필드를 초기화하는 생성자

 

  1. Person, Person의 자식 Student, Student의 자식 ForeignStudent를 클래스로 작성한다.
  2. Person 타입 배열이 Person, Student, ForeignStudent 타입의 객체를 1개씩 포함하며, Person 타입 배열 원소를 for~each 문을 사용해 각 원소의 정보를 다음과 같이 출력하도록 테스트 프로그램을 작성하시오.

정답

public class Person {
    private int age;
    private String name;
    Person(int age,String name){
        this.age=age;
        this.name=name;
    }
    public int get_age() {
        return age;
    }
    public String get_Name() {
        return name;
    }
    public void  show() {
        System.out.printf("사람[이름:%s, 나이%d]",get_Name(),get_age());
    }
}


public class Student extends Person{
    private int number;

    Student(int age, String name,int number) {
        super(age, name);
        this.number=number;
        // TODO Auto-generated constructor stub
    }
    public int get_number() {
        return number;
    }
    public void  show() {
        System.out.printf("사람[이름:%s, 나이%d, 학번:%d]",get_Name(),get_age(),get_number());
    }
}

public class ForeignStudent extends Student {
private String F;
    ForeignStudent(int age, String name,int number,String F) {
        super(age, name,number);
        this.F=F;
        // TODO Auto-generated constructor stub
    }
    public String get_F() {
        return F;
    }
    public void  show() {
        System.out.printf("사람[이름:%s, 나이%d, 학번:%d, 국적:%s]",get_Name(),get_age(),get_number(),get_F());
    }
    
    

}
public class Main {

    public static void main(String[] args) {
        Person[] p= {new Person(22,"김동이"),new Student(23,"황진이",100),new ForeignStudent(30,"amy",200,"USA")};
        
        for(Person i:p) {
            i.show();
            System.out.println();
        }
            }
        
        
        
    }
 

 생성자를 상속받는 경우 super()를 통해 부모에 있는 필드들을 가져온다. (오버라이딩)

생성자를 배열로 받는 방법은   클래스 []변수 = { new 클래스1(), new 클래스2() .... }; 이다.  


 

6.3   다음 표를 참고해 MovablePoint, MovablePoint의 부모 클래스인 Point를 작성하시오. Point 클래스의 toString() 메서드는 좌표를 나타내는 문자열이며, MovablePoint 클래스의 toString() 메서드는 좌표와 이동 속도를 나타내는 문자열을 반환한다.

 

  Point MovablePoint
필드 private int x,y private int xSpeed, ySpeed
메서드 접근자와 생성자, toString() 접근자와 생성자, toString()
생성자 Point(int x, int y) MoavablePoint(int x, int y, int xSpeed, int ySpeed)

 

정답

public class Point {
    private int x,y;
    Point(int x,int y){
        this.x=x;
        this.y=y;
    }
    int get_x() {
        return x;
    }
    int get_y() {
        return y;
    }
    public String toString() {
        return "x:"+get_x()+" y:"+get_y();
    }
}

public class MovablePoint extends Point{
  private int xSpeed,ySpeed;
  
  MovablePoint(int x,int y,int xSpeed,int ySpeed){
      super(x,y);
      this.xSpeed=xSpeed;
      this.ySpeed=ySpeed;
      }
  int get_xSpeed() {
      return xSpeed;
  }
  int get_ySpeed() {
      return ySpeed;
  }
  
  
    public String toString() {
        
        return super.toString()+"xspeed:"+get_xSpeed()+"yspeed:"+get_ySpeed();
    }
  
}
public class Main {

    public static void main(String[] args) {
        Point p =new Point(3,5);
        Point m =new MovablePoint(2,8,50,60);
        System.out.println(p.toString());
        System.out.println(m.toString());
        
        
    }
}

super.메소드() - 부모에있는 리턴 값을 가져온다 

 


6.5   다음 표를 참고해 Phone, Phone의 자식 클래스 Telephone, Telephone의 자식 클래스 Smartphone을 작성하고, 테스트 프로그램도 작성하시오.

  Phone Telephone Smartphone
필드 protected String owner private String when private String game
메서드 void talk() void autoAnswering() void playGame()

 

  1. 각 클래스에 모든 필드를 초기화하는 생성자를 추가한다.
  2. 각 클래스의 메서드를 구현한다. talk()는 owner가 통화 중, autoAnswering()은 owner가 부재중이니 when에 전화 요망, playGame()은 owner가 game 게임 중이라는 메시지를 출력한다.
  3. Phone, Telephone, Smartphone 객체로 Phone 타입 변수에 대입한다. 그리고 반복문과 조건문으로 실제 타입을 조사한 후 Phone 타입이면 talk(), Telephone 타입이면 autoAnswering(), Smartphone 타입이면 playGame()을 호출한다

 

정답

public class Phone {
    protected String owner;
    Phone(String owner){
        this.owner=owner;
    }
    void talk() {
        System.out.println("통화중");
    }
    
    
}

public class Telephone extends Phone{
    
private String when;

Telephone(String owner,String when){
        super(owner);
        this.when=when;
    }
String get_when() {
    return when;
}
void autoAnswering() {
    
    System.out.println(owner+"가 부재중이니 "+get_when()+"에 전화요망");
}
}

public class Smartphone extends Telephone{
    private String game;
 Smartphone(String owner,String game){
    super(owner,"emty");
    this.game=game;
}
String get_game() {
    return game;
    
}

void playGame() {
    System.out.println(owner+"가 게임중이니 "+get_game()+"에 전화요망");
}


}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Phone []p= {new Phone("황진이"), new Smartphone("민국이","갤러그"),new Telephone("길동이","내일")};
        
        
        for(Phone phone:p) {
            if(phone instanceof Smartphone) {
                ((Smartphone) phone).playGame();
            }else if(phone instanceof Telephone) {
             ((Telephone) phone).autoAnswering();
            }else {
                phone.talk();
            }
            
        }      
    }
}
 

 부모 instanceof 부모 : ok  (부모는 부모의 객체이다 ) o

 자식 instanceof 부모 : ok  (자식은 부모의 객체이다 ) 0

 부모 instanceof  자식 : not ok (부모는 자식의 객체이다 ?) x 

   for(int i=0;i<p.length;i++) {
            if(p[i] instanceof Smartphone) {
                ((Smartphone) p[i]).playGame();
            }else if(p[i] instanceof Telephone) {
                ((Telephone)p[i]).autoAnswering();
            }else {
                p[i].talk();
            }
            
            
        }

 

이렇게도 for문을 변경할 수있다. 이렇게 따로 for문을 돌려서 메소드를 실행할 경우에는 (클래스) 객체 로 형변환을

해줘야 한다.

 

 



6.6   운송 수단과 운송 수단의 하나인 자동차를 다음과 같이 모델링하려고 한다. 각 클래스의 show() 메서드는 필드 값을 출력한다. 두 클래스를 작성하고 아래 테스트 프로그램 OverrideTest를 실행해서 오버 라이딩된 메서드와 다형성 관계를 살펴보시오.

 

  Vehicle Car
필드 String color; //자동차 색상
int speed; //자동차 속도
int displacement; //자동차 배기량
int gears; //자동차 기어 단수
메서드 void show() void show()
생성자 public Vehicle(String, int) public Car(String, int, int, int)

 

public class OverrideTest {
    public static void main(String[] args) {
        Car c = new Car("파랑", 200, 1000, 5);
        c.show();

        System.out.println();
        Vehicle v = c;
        v.show();
    }
}

정답

public class Vehicle {
 static String color;
 static int speed;


Vehicle(String color,int speed){
    this.color=color;
    this.speed=speed;
}
static void show() {
    System.out.println(color);
    System.out.println(speed);
}

}
package src2;

public class Car extends Vehicle{
     static int displacement;
     static int gears;

Car(String color,int speed,int displacement,int gears){
    super(color,speed);
    this.displacement=displacement;
    this.gears=gears;
}
static void show() {
    System.out.println(color);
    System.out.println(speed);
    System.out.println(displacement);
    System.out.println(gears);
}

}
package src2;


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Car c=new Car("파랑",200,1000,5);
        Vehicle vv=new Vehicle("파랑",200);
        c.show();
        
        
        System.out.println();
        
        Vehicle v=c;
        v.show();

        
    }
}
 

 

정적 static 으로 선언하면 오버라이딩이 되지 않는다.

기본 메서드: Parents p = new Child();  ->자식이다!

정적 메서드: Parents p = new Child();  -> 부모다!

 

 

7장 

 

7.1   추상 클래스도 생성자를 가질 수 있다. 다음 표와 같이 추상 클래스와 구현 클래스를 작성한 후 아래 테스트 프로그램을 실행하시오. 단, 추상 클래스와 구현 클래스의 생성자는 모든 필드를 초기화한다.

 

추상 클래스 Abstract 구현 클래스 Concrete
필드 int i 필드 int i
추상 메서드 void show() 구현 메서드 void show()

 

public class AbstractTest {
    public static void main(String[] args) {
        Concrete c = new Concrete(100,50);
        c.show();
    }
}

 

정답

public abstract class Abstract {
     int i;
     
     abstract void show();
     
}


public class Concrete extends Abstract{
 int ii;
 Concrete(int i,int ii){
     this.i=i;
     this.ii=ii;
 }
 void show() {
     System.out.println("concrete"+i+""+ii);
 }
}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Concrete c=new Concrete(100,50);
        
        c.show();
                }
}

 

추상 클래스 선언 : abstract class 클래스이름{ ....}

추상 메서드 선언: abstract 반환타입 메서드이름();

추상클래스 -> 상속 시 무조건 정의를 내리게 강제추상 클래스 선언 : abstract class 클래스이름{ ....}

추상 메서드 선언: abstract 반환타입 메서드이름();

추상클래스 -> 상속 시 무조건 정의를 내리게 강제

 


7.3   가격 순서대로 정렬할 수 있는 Book 클래스와 다음 실행 결과가 나타나도록 테스트 프로그램을 작성하시오. Book 클래스에는 int 타입의 price 필드가 있으며, 생성자와 필요한 메서드를 포함한다. 또 테스트 프로그램은 3개의 Book 객체로 구성된 Book 배열을 사용해 가격 순서대로 정렬한 후 출력한다.

배열 books를 정렬하려면 Arrays.sort(books)를 호출하면 된다.

정답

public class Book implements Comparable<Book> {
int price;

Book(int price){
    this.price=price;
}
void price_arr() {
    System.out.println(price);
}

public int compareTo(Book o){
    if(this.price>o.price) {
        return 1;
    }else if(this.price==o.price) {
        return 0;
    }else {
        return -1;
    }
}}

import java.util.Arrays;

public class Books {

    public static void main(String[] args) {
        Book [] b= {new Book(1),new Book(500),new Book(5000),new Book(20)};
        
        Arrays.sort(b);
        for(Book i:b) {
        i.price_arr();
        }
    }

}
 

 

객체를  비교하기 위해서는 implements  Comparable를 사용해야한다.

implements 를 하면 반드시 compareTo()를 오버라이딩 해줘야 한다.

 

1. implements Comparable<객체 타입> 

2. public int compareTo(객체 o){....}

* a가 this b가 들어온 객체 라면 a>b: return +1, a<b: return -1, a=b: retrun 0  


7.4   다음 표와 같은 멤버를 가진 Controller 추상 클래스가 있다. TV와 Radio 클래스는 Controller의 구현 클래스이다. Controller, TV, Radio 클래스를 작성하시오. 그리고 ControllerTest 프로그램으로 테스트하시오.

 

필드 boolean power
메서드 void show()
추상 메서드 String getName()

정답

public abstract class Contoller {
	boolean power;
	Contoller(boolean power){
   		 this.power=power;
	}


void show() {
    if (power==true) {
        System.out.println(getName()+"켜졌습니다.");
    }else {
        System.out.println(getName()+"꺼졌습니다.");
    }
}
abstract  String getName();
}


public class TV extends Contoller{
    
TV(boolean power) {
        super(power);
        // TODO Auto-generated constructor stub
    }

public String getName() {
    return "tv";
    
}
}


public class Radio extends Contoller{

Radio(boolean power) {
        super(power);
        // TODO Auto-generated constructor stub
    }

String getName() {
    return "radio";
}
}

package src2;


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Contoller [] c= {new TV(false),new Radio(true)};
        
        for(Contoller d:c) {
            d.show();
        }

    }
}
 


7.8   다음과 같이 Human 인터페이스와 Human 구현 클래스인 Worker가 있다.

 

interface Human {
    void eat();
}

class Worker implements Human {
    public void eat() {
        System.out.println("빵을 먹습니다.");
    }
}

Worker 클래스는 이미 다른 프로젝트에서 사용 중이다. 그런데 Human 인터페이스를 구현한 Student 클래스에는 print() 메서드가 필요하다. 또 Human 타입으로 사용할 때도 echo() 메서드가 필요하다. 따라서 다음과 같은 테스트 프로그램을 실행하고자 한다. Human 인터페이스, Worker 클래스에 수정할 부분이 있으면 수정하고, Student 클래스도 작성하시오.

 

public class HumanTest {
    public static void main(String[] args) {
        Human.echo();

        Student s = new Student(20);
        s.print();
        s.eat();

        Human p = new Worker(); // 책에는 Person p = new Person();이라고 나와있는데
        p.print();              // 오타라고 생각해 문제에 맞게끔 임의로 수정했다.
        p.eat();
    }
}

정답

public interface Human {
void eat();
void print();
static void echo() {
    System.out.println("무야호");
};
}


public class Worker implements Human{
    public void eat() {
    System.out.println("빵을 먹습니다");
    }
    public void print() {
        System.out.println("인간 입니다.");
    }
    
}

public class Student implements Human{
int age;
Student(int age){
    this.age=age;
}
public void eat() {
    System.out.println("급식을 먹습니다.");
}
public void print() {
    System.out.println(age+"세의 학생입니다.");
}
}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Human.echo();
        
        Student s=new Student(30);
        s.print();
        s.eat();
        
        Human h=new Worker();
        h.print();
        h.eat();

    }
}

 

인터페이스에서 static 메서드를 사용하면 인터페이스내에서 구현을 할 수 있다. 

'JAVA > 쉽게 배우는 자바 프로그래밍 문제 풀이' 카테고리의 다른 글

문자열 practice 03_그룹 단어 체커  (0) 2021.10.27
    'JAVA/쉽게 배우는 자바 프로그래밍 문제 풀이' 카테고리의 다른 글
    • 문자열 practice 03_그룹 단어 체커
    문준영
    문준영
    공부한 내용 정리!

    티스토리툴바