기억보다 기록을

[JAVA] 자료구조_클래스, 객체, 참조변수 (1) 본문

Language/JAVA

[JAVA] 자료구조_클래스, 객체, 참조변수 (1)

juyeong 2022. 7. 2. 10:52
반응형

✔ 권오흠 교수님의 강의를 보고 정리했습니다. 

 

  • 클래스를 설계도라 부른다면 객체야 말로 그 안에 있는 집이다. 집은 늘 new 명령어로 생성될 수 있다.
  • new 명령어로 객체를 만들면, 그 객체는 고유한 이름을 가질 수 없다.
  • 그래서 우리에겐 참조변수가 필요하다. 그 객체에 접근할 수 있는 주소가 필요하다. (참조한다, 가리킨다라고 표현한다.)
  • 만들어진 객체는 이름이 없어서 참조변수를 하나 만들고 참조변수에 이름을 붙임으로서 만들어진 객체를 사용할 수 있게 된다.

🔻 Example1: Index Maker 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class IndexMaker {
    static String[] words = new String[100000];
    static int[] count = new int[100000];
    static int n = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("$ ");
            String command = sc.next();
            if (command.equals("read")) {
                String fileName = sc.next();
                makeIndex(fileName);
            } else if (command.equals("find")) {
                String str = sc.next();
                int index = findWord(str);
                if (index > -1) {
                    System.out.println("The word" + words[index] + "appears" + count[index] + "times.");
                } else
                    System.out.println("The word" + str + "does not appear.");

            } else if (command.equals("saveas")) {
                String fileName = sc.next();
                saveAs(fileName);

            } else if (command.equals("exit"))
                break;
        }

        sc.close();

        for (int i = 0; i < n; i++)
            System.out.println(words[i] + " " + count[i]);
    }

    // 리턴타입 애매하니까 void, static인 함수와 static이 아닌 함수의 차이. 자바에서는 메인만 스태틱인 경우가 많음
    static void makeIndex(String fileName) {
        try {
            Scanner inFile = new Scanner(new File(fileName));
            while (inFile.hasNext()) {
                String str = inFile.next();
                addWord(str);
            }
            inFile.close();

        } catch (FileNotFoundException e) {
            System.out.println("No File");
            return;
        }
    }

    static void addWord(String str) {
        int index = findWord(str); // return -1 if not found
        if (index != -1) { // found
            count[index]++;
        } else { // not found
            words[n] = str;
            count[n] = 1; // new words
        }
    }

    static int findWord(String str) {
        for (int i = 0; i < n; i++)
            if (words[i].equalsIgnoreCase(str)) // 대소문자 구분 X
                return i; // 일치하면 그냥 인덱스뱉고

        return -1; // for문을 나온 것은 다 검사했지만 찾는 단어가 없는 것이니 -1 리턴
    }

    static void saveAs(String fileName) {
        PrintWriter outFile;
        try {
            outFile = new PrintWriter(new FileWriter(fileName));
            for (int i = 0; i < n; i++)
                outFile.println(words[i] + " " + count[i]);
            outFile.close();

        } catch (IOException e) {
            System.out.println("save failed");
            return;
        }

    }
}

 

이 코드를 다음과 같은 방식으로 변경한다.

1. words, count 배열을 하나의 배열로 묶는다 ⇒ items[]

기존에 words,count로 선언되어있던 부분을 변경한다. items[].words , items[].count

2) 실행 시 nullPointException 에러를 처리한다.

 

🔻 Example1: 사각형의 면적

반응형