JAVA 11일차

MOZZI KIM·2022년 11월 7일
0

JAVA

목록 보기
11/21
post-thumbnail

1. this 와 this 생성자에 대하여 설명하시오.

this는 인스턴스 자신을 가르키는 참조 변수
this()생성자

this

class Car {
    String color; // 인스턴스 변수
    String gearType;
    int door; 
    
    Car(String color, String gearType, int door){
        this.color = color; 
        this.gearType = gearType;
        this.door = door;
    }
}
  • this 는 위 코드처럼 생성자의 매개변수로 선언된 변수의 이름이 인스턴스 변수와 같을 때,
    인스턴스 변수와 지역변수를 구분하기 위해서 사용한다.

  • Car() 생성자 안에서의 this.color는 인스턴스 변수이고, color는 매개변수로 정의된 지역변수이다.

  • static 메서드에서는 this를 사용하지 못한다.


this()

class Car{
	String color; // 인스턴스 변수
    String gearType;
    int door; 
    
    Car(){
        this("white", "auto", 4); // Car(String color, string gearType, int door)를 호출
    }
    
    Car(String color){
        this(color, "auto", 4);
    }
    
    Car(String color, String gearType, int door){
        this.color = color; 
        this.gearType = gearType;
        this.door = door;
    }
}
  • this()는 같은 클래스의 다른 생성자를 호출할 때 사용한다.
  • 위 코드의 Car() 생성자와 Car(String color) 생성자는 this()를 통해 모두 Car(String color, String gearType, int door) 생성자를 호출하고 있는 것이다.

2. 아래를 프로그래밍 하시오.

"Hello.java" 문자열에서 파일명과 확장자인 java를 분리시키는 프로그램을 짜시오.
 
입력: Hello.java
출력: 파일이름은:Hello 이며 확장자는 java 입니다.
public class separatePrac {

	public static void main(String[] args) {
		 // 1. split 할 문자열 준비
		System.out.print("파일명과 확장자 읿력: ");
		Scanner sc = new Scanner(System.in);
        String str = sc.next();
 
        // 2. "."를 구분자로 문자열 split
        String[] strArr = str.split("\\.");
        String name = strArr[0];
        String extension = strArr[1];
        
        // 3. 결과 출력
        System.out.println("출력: 파일이름은 " + name+ "이며 확장자는 " + extension +"입니다.");
        sc.close();
	}

}

3. 상속을 UML로 표기해 보세요.



4.부모클래스와 자식클래스의 다른 용어들은?

부모클래스는 상위클래스 또는 수퍼클래스
자식클래스는 하위클래스 또는 서브클래스


5. 2차원 배열의 디폴트 초기화 방법?

1. 디폴트 초기화

//기본 자료형 배열은 값을 안넣으면 모든 요소 0으로 초기화
int[] ar = new int[10]; //선언 객체생성

//인스턴스 배열(참조변수 배열)은 모든 요소 null로 초기화
String[] ar = new String[10];


2. 값을 넣어서 초기화

int[] ar = {1,2,4}
String course[] = {"Java", "C++", "HTML5"};

6. enhenced for 문에 대하여 설명하시오.

for( declaration : expression ) {
  // statements (s)
}

변수 선언(declaration) 다음에 배열 또는 배열을 리턴하는 함수(expression)가 들어온다. 즉, 배열항목을 처음부터 하나씩 변수에 대입하여 실행을 하다는 것이다.

향상된 for 문은 배열에만 사용할 수 잇고, 배열 값을 바꾸지는 못한다는 단점이 있다.


7. 아래의 프로그램을 짜시오. (필수)

4 x 42차원 배열을 만들고,
이곳에 1에서 10까지 범위의 정수를 랜덤하게 생성하여 정수 16개를 배열에 저장하고, 
2차원 배열을 화면에 출력하라.
8 6 1 1
7 3 6 9
4 5 3 7
9 6 3 1
public class ArrayRandom {

	public static void main(String[] args) {
		
		int[][] arr = new int[4][4];
		
		for(int i=0; i<arr.length; i++) {
			for(int j=0; j<arr[i].length; j++) {
				arr[i][j]= (int)(Math.random()*10)+1;
			}
		}
		for (int[] is : arr) {
			for (int is2 : is) {
				
				System.out.print(is2 + " ");
			}
			System.out.println();
		}
	}

}

8. 아래를 메모리 구조로 표현 하시오.

int[][] arr = new int[3][4]


9. 코딩연습

2차원 배열의 행과 열의 크기를 사용자에게 직접 입력받되, 1~10사이 숫자가 아니면
“반드시 1~10 사이의 정수를 입력해야 합니다.” 출력 후 다시 정수를 받게 하세요.
크기가 정해진 이차원 배열 안에는 영어 대문자가 랜덤으로 들어가게 한 뒤 출력하세요.
(char형은 숫자를 더해서 문자를 표현할 수 있고 65A를 나타냄, 알파벳은 총 26글자)

실행화면
==================================
행 크기 : 5
열 크기 : 4
T P M B
U I H S
Q M B H
H B I X
G F X I
import java.util.*;

public class RandomArray {

	public static void main(String[] args) {
		
		int row, col;
		while(true) {
			System.out.println("행과 열의 크기를 입력해주세요.");
			Scanner sc = new Scanner(System.in);
			row = sc.nextInt();
			col = sc.nextInt();
			System.out.println("행 크기 : " + row);
			System.out.println("열 크기 : " + col);

			if((1>row || row>=10) || (1>col || col>=10)) {
				System.out.println("반드시 1~10 사이의 정수를 입력해야 합니다.");
				continue;
			}
			else {
				break;
			}
		}
		char[][] arr = new char[row][col];
		for(int i=0; i<arr.length; i++) {
			for(int j=0; j<arr[i].length; j++) {
				arr[i][j] = (char)((int)(Math.random()*26) + 65);
			}
		}
		for (char[] is : arr) {
			for (char is2 : is) {
				System.out.print(is2 + " ");
			}
			System.out.println();
		}
	}

}
profile
코린이

0개의 댓글