생활코딩_Java

5w31892p·2022년 10월 20일
0

생활코딩

목록 보기
5/5

1. Java 설치 및 세팅

  1. JDK (java development kit)

  2. java8 설치 및 환경 변수 설정

  3. CMD에 java -version, javac -version 확인

  4. 이클립스 설치

2. Java 실행

public class HelloWorldapp { // 지정한 파일명과 같아야 함
    public static void main(String[] args) { 
        System.out.println("Hello World!");
    }
}

// 설명
public class HelloWorldapp {
// 파일의 이름과 똑같은 클래스를 찾고
	public static void main(String[] args) { 
    // main이라는 메소드를 찾아서
        System.out.println("Hello World!");
        // 이 중괄호 안에 위치한 코드 실행하도록 약속
    }
}

2-1. Java 동작 원리

  1. 확장자가 .java인 Java Source Code를 Compile하면 .class 라는 확장자를 가진 Java Application이 생성됨

  2. run 시키면 JVM(Java Virtual Machine)이 확장자가 .class인 파일을 읽어서 컴퓨터를 동작시킴

※ Source Code란?
사람이 이해할 수 있는 언어
기계는 이해할 수 없음

※ Compile이란?
확장자가 .java인 파일을 기계가 이해할 수 있도록 전환하는것 (.java 를 .class로 전환)

※ JVM이란?
Java Virtual Machin 즉 자바를 실행하는 가상기계
.class 파일을 읽어서 동작시킴

2-2. 자바 기술 응용

  1. 데스크탑 앱 만들기

    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    public class HelloWorldGUIApp{
        public static void main(String[] args){
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("HelloWorld GUI");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setPreferredSize(new Dimension(300, 200));
                    JLabel label = new JLabel("Hello World!!", SwingConstants.CENTER);
                    frame.getContentPane().add(label);
                    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
                    frame.setLocation(dim.width/2-400/2, dim.height/2-300/2); // 창 뜨는 위치 조절
    
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    }
  2. 사물 제어하기 (IoT)

  3. 안드로이드 앱 만들기
    Android Studio Download

3. 데이터와 연산

3-1. 데이터 코드로 표현하는 방법

  1. 단축키
    sout ⇾ System.out.println();
    psvm ⇾ public static void main(String[] args) { }

  2. 데이터 타입별로 고유한 특성이 있기에 String ("") Number ()을 나누어 사용

    public class Datatype {
        public static void main(String[] args) {
            System.out.println(6); // 숫자
            System.out.println("six"); // 문자열
            System.out.println("6"); // 문자열 6
            System.out.println(6+6); // 12
            System.out.println("6"+"6"); // 66
            System.out.println(6*6); // 36
    //        System.out.println("6"*"6"); // 에러, 문자는 곱하기 안됨
            System.out.println("1111".length()); // 4
    //        System.out.println(1111.length()); // 에러, 숫자는 길이 셀 수 없음
        }
    }

4. 숫자와 연산

  1. Math.
    수학관련 명령어 캐비넷

  2. Math.floor
    내림

  3. Math.ceil
    올림

  4. Math.PI
    원주율

  5. Math.min(1,2)
    두 값 중 더 작은값 출력

  6. Math.sqrt(4)
    루트값 출력

public class Number {
    public static void main(String[] args) {
        // Operator
        System.out.println(6 + 2); // 8
        System.out.println(6 - 2); // 4
        System.out.println(6 * 2); // 12
        System.out.println(6 / 2); // 3

        System.out.println(Math.PI); // 3.141592653589793
        System.out.println(Math.floor(Math.PI)); // 3, floor는 내림 (뒤에 소수점 아예 없애버리는 것)
        System.out.println(Math.ceil(Math.PI)); // 4, ceil은 올림
        System.out.println(Math.min(1,2)); // 1, 둘 중 더 작은 값
        System.out.println(Math.max(1,2)); // 2, 둘 중 더 큰 값
        System.out.println(Math.sqrt(4)); // 2, 루트 값 
    }
}

5. 문자열 다루기

5-1. 문자열 표현

  1. 자바에서 작은따옴표는 한글자를 표현하는 character

  2. character들이 모여 있는 것이 String

  3. \n
    줄바꿈

public class StringApp {
    public static void main(String[] args) {

        // Character VS String
        System.out.println("Hello"); // string (문자, character모음)
        System.out.println('H'); // character (한글자만 표현)
        System.out.println("H"); // string

        System.out.println("Hello " +
                "world"); // 엔터키 누르면 에디터 내에서만 줄이 바뀐 것처럼 보이는 것
        // New line
        System.out.println("Hello \nWorld"); // 줄바꿈

        // Escape
        System.out.println("Hello \"World\""); // 따옴표 일반 문자열 만드려면 앞에 \ 붙히기
        // Hello "World"
    }
}

5-2. 문자열 다루기

  1. .length()
    글자 수 세기

  2. .replace("a", "b")
    a를 b라는 문자로 대체, 변경

public class StringOperation {
    public static void main(String[] args) {
        System.out.println("Hello World".length()); // 11
        System.out.println("Hello, [[[name]]] ... bye.".replace("[[[name]]]", "5w31892p")); // 문자열 변경
    }
}

6. 변수 (Variable)

6-1. 정의

  1. 데이터 타입을 지정을 하지 않으면 자바는 무엇을 담아야 할 지 모름

  2. 즉 컴파일이 안되는 것

  3. 따라서 변수에 데이터 타입을 지정해주어야 컴파일이 진행 가능

  4. 자바는 변수를 만들 때 변수 안에 어떤 데이터 타입 들어갈 수 있는지 지정해야 함
    1) 정수 : int
    2) 실수 : double
    3) 문자열 : String

    public class variable {
        public static void main(String[] args) {
            int a = 1; // number > integer ... -2, -1, 0, 1, 2...
            System.out.println(a);
    
            double b = 1.1; // real number ? double ... -2.0, -1.0, 0, 1.0, 2.0...
            System.out.println(b);
    
            String c = "Hello World";
            System.out.println(c);
        }
    }

6-2. 효용

  1. 코드는 가독성이 좋아야 함

  2. 가독성이 좋으려면 값에 이름 부여해야 하기 때문에 변수 이용하면 좋음

  3. 코드를 빨리 파악할 수 있도록 코드 작성하는 것은 가장 중요한 일

  4. 그 가장 중요한 수단이 변수

     public class Letter {
        public static void main(String[] args) {
            String name = "5w31892p";
            System.out.println("Hello, "+name+" ... "+name+" ... 5w31892p ... bye!");
    
            double VAT = 10.0;
            System.out.println(VAT);
        }
    }

6-3. 데이터 타입의 변환 (Casting)

  1. 데이터 타입을 다른 데이터 타입으로 컨버팅한는 방법

  2. int - > double 형태로 바꿀 때는 자동으로 변환
    1) 손실 없음
    2) 손실이 없기 때문에 자동으로 캐스팅 해준 것

    double b = 1; == double b = (double) 1;
  3. double - > int 형으로 변환을 할 때는 손실값이 생기기 때문에 명시적으로 변환해야 함
    1) 실수를 정수로 바꾸면 소수점 아래 완전 사라져 손실이 있기 때문에 자동 캐스팅 안해준 것

  4. 숫자를 문자로
    Integer.toString(1);

  5. 데이터 타입 알려주는 코드
    System.out.println(변수명.getClass());

    public class Casting {
        public static void main(String[] args) {
    
            double a = 1.1; // 1.1
            double b = 1; // 1.0, 자동 컨버팅
            double b2 = (double) 1; // 1.0, 수동 컨버팅
            System.out.println(b);
    
    //        int c = 1.1;
            double d = 1.1; // 1.1
            int e = (int) 1.1; // 1
            System.out.println(d);
    
            // 1 to String
            String f = Integer.toString(1);
            System.out.println(f.getClass()); // class java.lang.String
    
        }
    }

7. 프로그래밍

7-1. 프로그래밍이란?

프로그래밍이란 자동화다!

  1. 프로그램
    시간의 순서에 따라서 어떠한 일이 일어나고 있는 것

    public class Program {
        public static void main(String[] args) {
    
            System.out.println(1);
            System.out.println(2);
            System.out.println(3);
        }
    }
  2. 프로그래밍
    1) 컴퓨터 각 기능을 취지에 맞게 배치하면 컴퓨터가 순차적으로 작업 실행하는 것을 통해 자동화 할 수 있음
    2) 자동화된 처리를 하기 위해 프로그래밍 언어 사용

  3. 프로그래밍을 통해 얻을 수 있는 효과
    1) 순차적으로 실행 되는 것을 통해 사람이 못한느 일을 기계에 위힘해 자동화 할 수 있음
    2) 이런 자동화 하는 것을 해주는 언어 중 하나가 Java

7-2. IoT 프로그램 만들기

IoT라이브러리 설치

다운받은 org 파일을 부품으로 사용
  1. org 폴더 내 엘리베이터 파일 불러오기 (import)

  2. 호출 명령

  3. 중복 제거 - id로 설정해주기
    1) 추후 변경할 때에도 편리

    import org.opentutorials.iot.Elevator;
    import org.opentutorials.iot.Security;
    import org.opentutorials.iot.Lighting;
    
    public class OKJavaGoInHome {
        public static void main(String[] args) {
    
            String id = "JAVA APT 507";
    
            // Elevator call
            Elevator myElevator = new Elevator(id);  // Elevator : 데이터타입, myElevator : 변수
            myElevator.callForUp(1); // 1층으로 호출 명령
    
            // Security off
            Security mySecurity = new Security(id);
            mySecurity.off();
    
            // Light on
            Lighting hallLamp = new Lighting(id+" / Hall Lamp");
            hallLamp.on();
    
            Lighting floorLamp = new Lighting(id+" / floor Lamp");
            floorLamp.on();
        }
    }

8. 디버거

코딩이 편해질 수 있는 지름길 = 디버거

  1. bug : 코드의 어떤 의도하지 않은 문제
  2. debugging : bug를 잡는 행위
  3. debugger : debugging 할 때 사용하는 도구

8-1. 디버깅 하는 방법

  1. 브레이크 포인트 설정

  2. run 아래 debug 클릭

  3. 하나하나 말고 한번에 쭉 디버깅 하고 싶은 곳에 브레이크 포인트로 지정
    1) Resume 누르면 다음 브레이크 포인트 있는 곳 까지 쭉 실행됨

  4. stop 눌러서 종료

8-2. 아이콘

  1. Resume (플레이버튼)
    다음 Break Point로 이동

  2. step over
    1) 다음 줄로 이동 (명령어 1개만 실행)
    2) 프로그램 한줄씩 실행 가능
    3) 실행되는 순간 변수의 상태 체크 가능

  3. step into
    1) 메소드(명령어)가 어떻게 되어 있는지 볼 수 있음
    2) 즉 내부(메소드)로 이동

  4. Step Out
    현재 break된 라인에서 호출한 곳으로 빠져나가기

  5. return
    처음 디버그한 파일로 이동

  6. stop
    중지

9. 입력과 출력

프로그램이란 입력을 출력하는 기계

입력 (input)

  1. Argument : 텍스트 정보
  2. File : 파일 내용
  3. Network : 웹사이트 정보
  4. Audio : 음성
  5. Program : 다른 프로그램 출력 결과

출력 (output)

  1. Monitor
  2. File
  3. Audio
  4. Program

9-1. 입력값에 따라 달라지는 출력값 만들기

어떤 인풋이 있는지, 그 인풋을 어떻게 프로그램 안으로 끌고 들어올 수 있는지를 익히는 것 중요함

  1. id값을 프로그램 실행할 때마다 바꾸는 것은 비효율적

  2. 프로그램 실행하면 사용자가 정보 입력하여 id값 세팅

  3. 정보 입력 가능한 팝업창 띄우는 방법
    검색 키워드 : java popup input text swing
    1) JOptionPane 임포트해야 함

String 변수명 = JOptionPane.showInputDialog("Enter a 변수명");
  1. run 누르면 정보 입력할 수 있는 팝업창 뜸

  2. 정보 입력 후 확인 눌러야 java 실행 됨
    → 값 입력 전까지 자바는 실행을 멈춰있다가 입력 후 확인 누르면 실행 됨

  3. 입력 값에 따라 동작하게 됨

  4. String을 double로 컨버팅하는 방법
    검색 키워드 : java string to double conversion

    String 변수명 = "12.34"; // example String
    double value = Double.parseDouble(변수명);
  5. 완성

    import org.opentutorials.iot.DimmingLights;
    import org.opentutorials.iot.Elevator;
    import org.opentutorials.iot.Lighting;
    import org.opentutorials.iot.Security;
    
    import javax.swing.JOptionPane;
    
    public class OKJavaGoInHomeInput {
        public static void main(String[] args) {
    
            String id = JOptionPane.showInputDialog("Enter a ID");
            String bright = JOptionPane.showInputDialog("Enter a bright level");
    
            // Elevator call
            Elevator myElevator = new Elevator(id);  // Elevator : 데이터타입, myElevator : 변수
            myElevator.callForUp(1); // 1층으로 호출 명령
    
            // Security off
            Security mySecurity = new Security(id);
            mySecurity.off();
    
            // Light on
            Lighting hallLamp = new Lighting(id+" / hallLamp");
            hallLamp.on();
    
            Lighting floorLamp = new Lighting(id+" / floorLamp");
            floorLamp.on();
    
            DimmingLights moodLamp = new DimmingLights(id+" / moodLamp");
            moodLamp.setBright(Double.parseDouble(bright)); // 10의 밝기로
            moodLamp.on();
        }
    }

9-2. Arguments & Parameter

args라는 Parameter를 통해서 받는 것
프로그램이 실행될 때 입력 값을 받는 가장 표준적인 방법

Parameter에 여러 값이 들어올 경우에는 대괄호 안에 0, 1 등과 같이 몇번째에 있는 값인지 적기

  1. Arguments (인자)
    1) 메뉴 Run
    2) Edit Configurations
    3) Program arguments 에 큰따옴표로 구분해서 값 추가

  2. Parameter (매개변수)
    1) args 변수에 입력한 값 들어옴
    2) arguments에 들어온 값 출력

    // Parameter, 매개변수 = args
       public static void main(String[] args) {
       	String id = args[0];
           String bright = args[1];
       }
  3. 완성

    import org.opentutorials.iot.DimmingLights;
    import org.opentutorials.iot.Elevator;
    import org.opentutorials.iot.Lighting;
    import org.opentutorials.iot.Security;
    
    public class OKJavaGoInHomeInput {
    
        // Parameter, 매개변수 = args
        public static void main(String[] args) {
    
            String id = args[0];
            String bright = args[1];
    
            // Elevator call
            Elevator myElevator = new Elevator(id);  // Elevator : 데이터타입, myElevator : 변수
            myElevator.callForUp(1); // 1층으로 호출 명령
    
            // Security off
            Security mySecurity = new Security(id);
            mySecurity.off();
    
            // Light on
            Lighting hallLamp = new Lighting(id+" / hallLamp");
            hallLamp.on();
    
            Lighting floorLamp = new Lighting(id+" / floorLamp");
            floorLamp.on();
    
            DimmingLights moodLamp = new DimmingLights(id+" / moodLamp");
            moodLamp.setBright(Double.parseDouble(bright)); // 10의 밝기로
            moodLamp.on();
        }
    }

10. 자바 문서 보는 법

10-1. API, UI

  1. API (application programming interface)
    1) 다른 프로그램에서 부품으로 사용
    2) 자바가 기본적으로 제공하는 부품들의 조작 방법

  2. UI (user interface)
    사용자가 프로그램을 조작하기 위해서 사용하는 조작 장치

10-2. 패키지, 클래스

  1. api documention java
    자바 공식 문서

  2. 패키지
    1) 서로 연관된 비슷한 성격의 클래스를 모아서 이름을 붙인 것
    ex) java.lang : Math 클래스가 소속되어 있는 패키지

  3. 클래스
    서로 연관된 변수와 메소드를 모아서 이름을 붙인 것
    ex) ex) Math는 PI,floor, ceil 등의 여러 메소드 그룹핑 한 클래스

10-3. 클래스

서로 연관된 변수와 메소드들을 모아서 거기다 이름을 붙인 것

public class ClassApp {
    public static void main(String[] args) {

        //클래스.변수 → Math.PI
        //클래스는 서로 연관된 변수와 메소드들을 모아서 거기다 이름을 붙인 것

        System.out.println(Math.PI); // 3.141592653589793
        System.out.println(Math.floor(1.6)); // 내림, 1.0
        System.out.println(Math.ceil(1.6)); // 올림 2.0
    }
}

10-4. 인스턴스

  1. PrintWriter 클래스 이용 (Math와 사용법 다름)

  2. new를 붙혀 복제한 결과를 변수에 담음

  3. Math 같은 클래스는 일회성 작업

  4. 파일에 대한 여러가지 작업이 필요한 경우
    new를 붙여 복제해 각 다른 상태를 가지고 있는 인스턴스를 만들어 사용 하는 것이 효율적

  5. 즉 일회성이 아닌 긴 맥락의 작업인 경우 클래스를 복제한 인스턴스를 만들어서 사용

  6. 공식 문서에 Constructor (생성자)라는 것이 없으면 일회성 (Math, System 등은 일회성)

  7. Constructor(생성자)가 없는 Class
    1) Instance를 사용 불가
    2) 간단한 일회성 작업을 수행하는 Class
    3) Library 가 기본 내장되어 있어 Library를 Import 할 필요 없음

  8. Constructor 있는 Class
    1) Library를 Import 하여야 함
    2) 연관되여 사용하는 Class의 Library 도 Import 하여야 함

인스턴스 개념

System.out.println(Math.PI);
System.out.println(Math.floor(1.6));

위와같은 방법으로 하는 것이 짧은 맥락의 작업에는 빠르겠지만
파일을 수정한다는 것은 파일 하나만 수정하는 것이 아니라
그 파일에 대한 여러가지 작업들이 후속으로 생기고
동시에 여러개의 파일을 작업해야 할 가능성이 높음

이런 경우에는 하나의 클래스를 사용하기보다는
new를 이용해서 클래스를 복제하여
각각의 다른 상태인 instance를 만들어서 사용하는것이 더 효율적임

  1. 클래스를 사용할 때 인스턴스로 활용하기 원하는 것은 Constructor 라는 것을 가지고 있음

  2. new 뒤에 붙힌 것이 바로 Constructor

  3. Constructor 앞에 new 붙이면 복제되서 인스턴스가 됨

10-5. 상속 (Inheritance)

PrintWriter Class → Writer Class 상속 받음
Writer Class → Object Class 상속 받음

Object > Writer > PrintWriter
Object 조부모
Writer 부모
PrintWriter 자식
  1. Class에 커서 두고 ctrl + h 누르면 상속 관계 볼 수 있음

  2. 모든 Class는 Object Class를 상속 받음

  3. 부모 클래스와 자식 클래스에 동일한 메소드나 변수 있는 경우
    Overtide라는 부모 클래스 작업 무시되고 자식 클래스의 작업이 수행됨

  4. Override = 덮어쓰기

  5. 자바에서는 변수를 필드라고 함

11. 앱 만들기 1

11-1. 기본 기능 구현

  1. 기준 값 바꾸기
    1) edit → find → replace
    2) 위에는 찾을 값 / 아래는 바꿀 값
    3) replace all

    public class AccountingApp {
        public static void main(String[] args) {
            System.out.println("Value of supply :"+10000.0); // 공급가
            System.out.println("VAT :"+ (10000.0*0.1)); // 부가가치세
            System.out.println("Total :"+ (10000.0 + 10000.0*0.1)); // 소비자가
            System.out.println("Expense :"+ (10000.0*0.3)); // 비용
            System.out.println("Income :"+ (10000.0 - 10000.0*0.3)); // 이익
            System.out.println("Dividend 1 :"+ (10000.0 - 10000.0*0.3) * 0.5 ); // 배당
            System.out.println("Dividend 2 :"+ (10000.0 - 10000.0*0.3) * 0.3 ); // 배당
            System.out.println("Dividend 3 :"+ (10000.0 - 10000.0*0.3) * 0.2 ); // 배당
        }
    }

11-2. 변수 도입

  1. 한번에 변수화
    1) 드래그 후 마우스 우클릭 refactor → introduce variable
    2) 단축키 : crtl + alt + v
    3) 이름 설정

  2. 값은 같으나 다 바꾸면 안되는 경우
    1) 먼저 변수명을 적고
    2) create local variable ~~ 눌러서 만들고
    3) 변수로 바꿀 부분에만 변수명 입력

  3. 변수명으로 바뀌지 않은 부분 있다면 변경

    public class AccountingApp {
        public static void main(String[] args) {
    
            double valueOfSupply = 10000.0;
            double vatRate = 0.1;
            double expenseRate = 0.3;
            double VAT = valueOfSupply * vatRate;
            double total = valueOfSupply + VAT;
            double expense = valueOfSupply * expenseRate;
            double income = valueOfSupply - expense;
            double dividend1 = income * 0.5;
            double dividend2 = income * 0.3;
            double dividend3 = income * 0.2;
    
            System.out.println("Value of supply :"+ valueOfSupply); // 공급가
            System.out.println("VAT :"+ VAT); // 부가가치세
            System.out.println("Total :"+ total); // 소비자가
            System.out.println("Expense :"+ expense); // 비용
            System.out.println("Income :"+ income); // 이익
            System.out.println("Dividend 1 :"+ dividend1); // 배당
            System.out.println("Dividend 2 :"+ dividend2); // 배당
            System.out.println("Dividend 3 :"+ dividend3); // 배당
        }
    }

11-3. 입력값 도입

입력값을 주면 그에 따라서 서로 다른 출력 값 만들어내기

  1. Arguments에 값 입력

  2. 넣고 가격 넣었던 자리에 arge[0]; 넣기
    1) 문자열을 double데이터타입에 넣으려고 해서 오류 발생
    2) 검색어 : string to double java

    String text = "12.34"; // example String
    double value = Double.parseDouble(text);
  3. 완성

    public class AccountingApp {
        public static void main(String[] args) {
    
            double valueOfSupply = Double.parseDouble(args[0]);
            double vatRate = 0.1;
            double expenseRate = 0.3;
            double VAT = valueOfSupply * vatRate;
            double total = valueOfSupply + VAT;
            double expense = valueOfSupply * expenseRate;
            double income = valueOfSupply - expense;
            double dividend1 = income * 0.5;
            double dividend2 = income * 0.3;
            double dividend3 = income * 0.2;
    
            System.out.println("Value of supply :"+ valueOfSupply); // 공급가
            System.out.println("VAT :"+ VAT); // 부가가치세
            System.out.println("Total :"+ total); // 소비자가
            System.out.println("Expense :"+ expense); // 비용
            System.out.println("Income :"+ income); // 이익
            System.out.println("Dividend 1 :"+ dividend1); // 배당
            System.out.println("Dividend 2 :"+ dividend2); // 배당
            System.out.println("Dividend 3 :"+ dividend3); // 배당
        }
    }

에디터 켜지 않고 값 바꾸는 방법

  1. 해당 파일 저장경로 복사

  2. GitBash 열기
    주소에 띄어쓰기가 있을 경우 큰따옴표로 감싸기

cd "D:\user\Desktop\생활코딩\03_java\5. My App"lsrm AccountingApp.class
↓
ls -al
↓
javac AccountingApp.java
# class 파일 없을 시 javac로 컴파일 해서 생성ls -al
↓
java AccountingApp 20000.0 
# 뒤에 값을 안넣으면 에러

12. 앱 만들기 2

12-1. 조건문

1만원보다 클 경우엔 5:3:2
1만원보다 작을 경우 1:0:0
  1. if else

    public class AccountingIFUnder10000App {
    
        public static void main(String[] args) {
    
            double valueOfSupply = Double.parseDouble(args[0]);
            double vatRate = 0.1;
            double vat = valueOfSupply * vatRate;
            double total = valueOfSupply + vat;
            double expenseRate = 0.3;
            double expense = valueOfSupply * expenseRate;
            double income = valueOfSupply - expense;
    
            double Dividend1;
            double Dividend2;
            double Dividend3;
    
            if (income > 10000.0) {
                Dividend1 = income * 0.5;
                Dividend2 = income * 0.3;
                Dividend3 = income * 0.2;
            } else {
                Dividend1 = income * 1.0;
                Dividend2 = income * 0;
                Dividend3 = income * 0;
            }
    
            System.out.println("Value of supply :" + valueOfSupply);
            System.out.println("VAT :" + vat);
            System.out.println("Total :" + total);
            System.out.println("Expense :" + expense);
            System.out.println("Income :" + income);
            System.out.println("Dividend 1 :" + Dividend1);
            System.out.println("Dividend 2 :" + Dividend2);
            System.out.println("Dividend 3 :" + Dividend3);
        }
    }

12-2. 배열

배열이란?

서로 연관된 데이터를 정리정돈 하는 수단

  1. 변수가 많아질수록 그 변수가 더럽혀질 가능성이 커짐

    double rate1 = 0.5;
    double rate2 = 0.3;
    double rate3 = 0.2;
    
    double dividend1 = income * rate1;
    double dividend2 = income * rate2;
    double dividend3 = income * rate3;
  2. 그래서 배열을 만들어 하나의 변수로 만들어 값 여러개 넣기

  3. 연관된 값이라는 것을 알 수 있게 됨

  4. 하나의 변수만 존재하기 떄문에 변수 오염될 가능성 줄어듬

    double valueOfSupply = Double.parseDouble(args[0]);
    double vatRate = 0.1;
    double vat = valueOfSupply * vatRate;
    double total = valueOfSupply + vat;
    double expenseRate = 0.3;
    double expense = valueOfSupply * expenseRate;
    double income = valueOfSupply - expense;
    
    double[] dividendRates = new double[3];
    dividendRates[0] = 0.5;
    dividendRates[1] = 0.3;
    dividendRates[2] = 0.2;
    
    double dividend1 = income * dividendRates[0];
    double dividend2 = income * dividendRates[1];
    double dividend3 = income * dividendRates[2];

12-3. 반복문

동업자가 1만명이라고 가정
  1. while
    1) 배열과 단짝
    2) 코드가 간결해짐

     double valueOfSupply = Double.parseDouble(args[0]);
     double vatRate = 0.1;
     double vat = valueOfSupply * vatRate;
     double total = valueOfSupply + vat;
     double expenseRate = 0.3;
     double expense = valueOfSupply * expenseRate;
     double income = valueOfSupply - expense;
    
     double[] dividendRates = new double[3];
     dividendRates[0] = 0.5;
     dividendRates[1] = 0.3;
     dividendRates[2] = 0.2;
    
     int i = 0;
     while (i < dividendRates.length) {
     System.out.println("Dividend :"+ income * dividendRates[i]);
     i = i + 1;

12-4. 메소드

메소드란?

서로 연관된 코드를 그룹핑해서 이름을 붙힌 정리정돈 상자

vat 변수 코드가 엄청 복잡한 수식의 코드라면?
  1. 변경할 코드 드래그 우클릭 refactor → extract method
    1) 단축키 : ctrl + alt + m

  2. valueOfSupply를 AccountingMethodApp의 전역변수로 만들기
    1) 모든 메소드에서 접근이 가능해짐
    2) main 바깥쪽에서 선언
    3) getVat 뒤쪽 괄호에 valueOfSupply 안적어도 됨

  3. vatRate도 전역변수로 만들기
    1) 우클릭 refactor → introduce fileld
    2) 단축키 : ctrl + alt + f
    3) 앞이 public으로 시작 하지 않는다면 public으로 바꿔주기

  4. vatRate처럼 valueOfSupply도 선언은 바깥쪽에서, 값은 main 안에서

public class AccountingMethodApp {
    public static double valueOfSupply;
    public static double vatRate;
    public static double expenseRate;
    public static void main(String[] args) {
        valueOfSupply = 10000.0;
        vatRate = 0.1;
        expenseRate = 0.3;
        print(); // 메소드 호출은 print 처럼 get으로 불러오면 됨
    }

    public static void print() {
        System.out.println("Value of supply :"+ valueOfSupply);
        System.out.println("VAT :"+ getVat());
        System.out.println("Total :"+ getTotal());
        System.out.println("Expense :"+ getExpense());
        System.out.println("Income :"+ getIncome());
        System.out.println("Dividend 1 :"+ getDividend1());
        System.out.println("Dividend 2 :"+ getDividend2());
        System.out.println("Dividend 3 :"+ getDividend3());
    }

    // 메소드를 만드는 코드
    private static double getDividend1() {
        return getIncome() * 0.5;
    }
    private static double getDividend2() {
        return getIncome() * 0.3;
    }
    private static double getDividend3() {
        return getIncome() * 0.2;
    }
    private static double getIncome() {
        return valueOfSupply - getExpense();
    }
    private static double getExpense() {
        return valueOfSupply * expenseRate;
    }
    private static double getTotal() {
        return valueOfSupply + getVat();
    }
    private static double getVat() {
        return valueOfSupply * vatRate;
    }
}

12-5. 클래스

클래스란?

서로 연관된 변수와 메소드를 그룹핑해서 이름을 붙힌 정리정돈 상자

  1. 아웃라인
    1) View => Tool Windows => Structure
    1) 단축키 : alt + 7
    2) 멤버 확인 : 클래스 소속의 변수, 메소드 포괄적으로 볼 수 있음

  2. 클래스 만들기

    class Accounting {
        public static double expenseRate;
        public static double valueOfSupply;
        public static double vatRate;
    
        public static void print() {
            System.out.println("Value of supply :" + valueOfSupply);
            System.out.println("VAT :" + getVat());
            System.out.println("Total :" + getTotal());
            System.out.println("Expense :" + getExpense());
            System.out.println("Income :" + getIncome());
            System.out.println("Dividend 1 :" + getDividend1());
            System.out.println("Dividend 2 :" + getDividend2());
            System.out.println("Dividend 3 :" + getDividend3());
        }
    
        private static double getDividend1() {
            return getIncome() * 0.5;
        }
    
        private static double getDividend2() {
            return getIncome() * 0.3;
        }
    
        private static double getDividend3() {
            return getIncome() * 0.2;
        }
    
        private static double getIncome() {
            return valueOfSupply - getExpense();
        }
    
        private static double getExpense() {
            return valueOfSupply * expenseRate;
        }
    
        private static double getTotal() {
            return valueOfSupply + getVat();
        }
    
        private static double getVat() {
            return valueOfSupply * vatRate;
        }
    }
    
    public class AccountingClassApp {
        public static void main(String[] args) {
                Accounting.valueOfSupply = 10000.0;
                Accounting.vatRate = 0.1;
                Accounting.expenseRate = 0.3;
                Accounting.print();
        }
    }

    1) 필드들 class 안으로 넣어 멤버로 만들기
    2) 메소드들도 class 멤버로 만들기
    3) main안에 있는 것들 앞에 클래스명. 다 붙혀주기
    4) 클래스명. 붙혀주는 것은 해당 클래스에 속해있는 것을 분명히 함으로 소속관계를 명확히 할 수 있음
    5) 다른 취지의 코드들과 뒤섞여도 상관 x
    6) print와 같이 흔한 이름의 메소드 사용해도 클래스만 다르다면 같은 이름의 메소드 공존 가능

12-6. 인스턴스

인스턴스란?

하나의 클래스를 복제해서 서로 다른 데이터의 값과 서로 같은 메소드를 가진 복제본을 만드는 것

  1. Class 복제
    1) 클래스에 new를 붙여 만든 것이 바로 인스턴스
    2) 변수타입.변수명 = new 복제할 클래스 ();로 인스턴스 생성

  2. 복제 완료했다면 main쪽 static만 빼고 static 다 지우기

    class Accounting {
        public double expenseRate;
        public double valueOfSupply;
        public double vatRate;
    
        public void print() {
            System.out.println("Value of supply :" + valueOfSupply);
            System.out.println("VAT :" + getVat());
            System.out.println("Total :" + getTotal());
            System.out.println("Expense :" + getExpense());
            System.out.println("Income :" + getIncome());
            System.out.println("Dividend 1 :" + getDividend1());
            System.out.println("Dividend 2 :" + getDividend2());
            System.out.println("Dividend 3 :" + getDividend3());
        }
    
        private double getDividend1() {
            return getIncome() * 0.5;
        }
    
        private double getDividend2() {
            return getIncome() * 0.3;
        }
    
        private double getDividend3() {
            return getIncome() * 0.2;
        }
    
        private double getIncome() {
            return valueOfSupply - getExpense();
        }
    
        private double getExpense() {
            return valueOfSupply * expenseRate;
        }
    
        private double getTotal() {
            return valueOfSupply + getVat();
        }
    
        private double getVat() {
            return valueOfSupply * vatRate;
        }
    }
    
    public class AccountingClassApp {
        public static void main(String[] args) {
    
            //instance
            Accounting a1 = new Accounting();
            a1.valueOfSupply = 10000.0;
            a1.vatRate = 0.1;
            a1.expenseRate = 0.3;
            a1.print();
    
            Accounting a2 = new Accounting();
            a2.valueOfSupply = 20000.0;
            a2.vatRate = 0.05;
            a2.expenseRate = 0.2;
            a2.print();
        }
    }
    

메소드 → 클래스 → 인스턴스로 프로그램의 구조를 짜나가는것

0개의 댓글