CS Fundamentals/Data Structures & Algorithms

[Data Structures] Variable & Custom Variable (Custom Data Type)

EndiYou 2025. 2. 19. 08:58

변수는 값을 담아두고 재사용하기 위해서 사용하는데, 변수의 기본적인 사용법과 Custom Data Type(Custom Variable Type) 사용법을 정리한다.


변수 초기화

// [Data Type] [Variable Name] = [Value]
String name = "GilDong";
  • 변수는 대입 연산자(=)를 이용해서 값을 메모리에 담는다.
  • 변수 초기화 과정: 메모리 확보 → 데이터 저장 → 메모리 주소를 Variable Name에 맵핑
  • 메모리 주소의 형태: (16진수) 0x00000000
  • 메모리를 확보하는 공간은 Data Type에 따라서 다르다. (char = 1byte, int = 4byte, double = 8byte)

 

변수의 종류

  • 전역 변수: 특정 함수에 종속 되지 않고 모든 영역에서 사용되는 변수
  • 지역 변수: 변수가 위치한 함수에 종속되어 해당 함수내에서만 사용되는 변수
  • 전역 변수와 지역 변수의 이름이 같을 경우 지역 변수가 우선 순위를 가진다.

 

Custom Data Type

변수를 선언할 때 Data Type을 지정해야 한다. 하나의 변수에는 하나의 Data Type만 지정할 수 있다. 하나의 변수에 여러 종류의 데이터 타입을 담고 싶거나 2개 이상의 값을 담고 싶은 경우 Custom Data Type을 만들어서 사용할 수 있다.

  • Custom Data Type 생성 및 초기화
class Person {
	String name;
	int age;
}

public class Main {
	public static void main(String[] args) throws Exception {
		Person person = new Person();
		person.name = "GilDong";
	}
}
  • 초기화 과정에 파라미터로 값 저장
class Person {
	String name;
	int age;
    
    public Person (String name, int age) {
    	this.name = name;
        this.age = age;
    }
}

public class Main {
	public static void main(String[] args) throws Exception {
		Person gd = new Person("GilDong", 30);
        Person mr = new Person("MongRyong", 20);
	}
}

 

Custom Data Type을 이용해 2차원 배열의 좌표 위치 저장하는 예제코드

  • Custom Data Type 만들기
 static class Node {
     int row;
     int col;

     public Node(int row, int col) {
         this.row = row;
         this.col = col;
     }
 }
  • 좌표 위치 저장할 배열 초기화
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
Node[] location = new Node[r*c + 1];
  • 배열에 값을 담으면서 좌표 위치를 저장하기
 for (int i=0; i<r; i++) {
     st = new StringTokenizer(br.readLine());
     for (int j=0; j<c; j++) {
         int now = Integer.parseInt(st.nextToken());
         arr[i][j] = now;
         location[now] = new Node(i, j);
     }
 }
더보기

전체 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class Node {
     int row;
     int col;

     public Node(int row, int col) {
         this.row = row;
         this.col = col;
     }
}

public class Main {

	 static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
	 static StringTokenizer st;
	 static int[][] arr; 
	 
	 public static void main(String[] args) throws IOException{
		 int r = Integer.parseInt(br.readLine());
         int c = Integer.parseInt(br.readLine());
		 arr = new int[r][c];
		 Node[] location = new Node[r * c + 1];
		 for (int i=0; i<r; i++) {
			 st = new StringTokenizer(br.readLine());
			 for (int j=0; j<c; j++) {
				 int now = Integer.parseInt(st.nextToken());
				 arr[i][j] = now;
				 location[now] = new Node(i, j);
			 }
		 }
	 }

}
반응형