본문 바로가기
코딩도전기/JAVA

CODO Day12_JAVA(type/method/문자열비교/switch/while/배열/클래스(API/Member(생성자))

by 코도꼬마 2023. 2. 16.

Type 최소/최대 값

public class MinMax {

	public static void main(String[] args) {
		System.out.println("int 최소값 : "+Integer.MIN_VALUE);
		System.out.println("int 최대값 : "+Integer.MAX_VALUE);
		
		System.out.println("long 최소값 : "+Long.MIN_VALUE);
		System.out.println("long 최대값 : "+Long.MAX_VALUE);
		
		System.out.println("float 최소값 : "+Float.MIN_VALUE);
		System.out.println("float 최대값 : "+Float.MAX_VALUE);
		
		System.out.println("double 최소값 : "+Double.MIN_VALUE);
		System.out.println("double 최대값 : "+Double.MAX_VALUE);

	}

}

 

 

Method

public class Toaster {

	 void main(String[] args) {  //함수(X),매서드(O)
		//매개변수 : 문자열 배열
		//반환값 : 없음
		String dish = toaster("식빵");
		System.out.println(dish);

	}

	String toaster(String 빵) {
		//매개변수 : 문자열
		//반환값 : 문자열
		return "구워진 빵";
	}
	
}

 

 

문자열 비교

public class Compare {

	public static void main(String[] args) {
		
		int v1 = 1;
		double v2 = 1.0;
		String str1 = "JAVA";
		String str2 = new String("JAVA");
		
		System.out.println(v1 == v2);
		System.out.println(str1 == str2);  //java에서는 문자열 비교를 이렇게 하면 안됨
		System.out.println(str1.equals(str2));

	}

}

 

 

Switch

public class SwitchStmt {

	public static void main(String[] args) {
		
		String item = "식혜";
		
		switch (item) { //JDK 1.6 이하에서는 switch문 값이 숫자만 들어가야한다.
		case "식혜":
			System.out.println("식혜가 나왔습니다.");
			break;

		default:
			System.out.println("해당 제품이 없습니다.");
		}

	}

}

 

 

While

public class WhileStmt {

	public static void main(String[] args) {
		
		int i =1;
		while (true) {
			i++;
			System.out.println("영원히 반복된다");
			if(i>=100) {
				break;
			}
		}

		//unreachable code : 위 구문대로라면 여기까지 코드가 닿지 않음
		//해결방법 1 : 코드를 지운다
		//해결방법 2 : 위 반복문이 정지할 수 있는 조건을 만들어준다
		int cup = 1;  
		
	}

}

 

Unreachable code

  • 위쪽에 위치한 코드가 무한루프에 걸릴 경우 실행되지 않는 코드
  • 해결방법 1 : 코드를 지운다
    해결방법 2 : 위 반복문이 정지할 수 있는 조건을 만들어준다

 

 

배열

  • 배열생성
public class ArrDefine {

	public static void main(String[] args) {
		//배열 생성
		//1.선언과 동시에 값을 넣음
		int[] scores = {70, 80, 90};  //추천방법
		String names[] = {"홍길동","고길동","박길동"};		
		
		//2. new 연산자로 값을 추가
		int[] numArr;
		numArr = new int[] {70,80,90};		
		
		//3.미리 크기를 지정
		int[] arr = new int[6];
	}

}

 

 

  • 배열에 값 넣기
public class Input {

	public static void main(String[] args) {
		
		int[] scores = new int[10];
		
		System.out.println("크기 확인 : " + scores.length);
		
		scores[0] = 100;
		scores[1] = 50;
		scores[2] = 70;
		
		//3~9번 방까지 80씩 넣기 
		for(int i=3; i<scores.length; i++) {
			scores[i] = 80;
		}		
		
	}

}

 

 

  • 배열에 넣은 값 꺼내기(For, ForEach)
public class Output {

	public static void main(String[] args) {
		
		int scores[] = new int[10];		
		
		for(int i=0; i<scores.length; i++) {
			scores[i] = (i+1)*10;
		}
		
//		System.out.println("0번 방의 값 : " + scores[0]);
//		System.out.println("5번 방의 값 : " + scores[5]);
//		System.out.println("9번 방의 값 : " + scores[9]);
		
		for(int i=0; i<scores.length; i++) {
			System.out.println(i+"번 방의 값 : " + scores[i]);
		}
		

	}

}

 

public class ForEach {

	public static void main(String[] args) {

		int[] score = {95,75,84,35,88};
		
		//일반적인 for문 : 시작과 끝을 지정할 수 있음
		for (int i = 0; i < score.length; i++) {
			System.out.println(score[i]);
		}
		
		System.out.println("---------------------------");
		
		//향상된 for문 : 시작하면 모든 내용을 꺼냄
		for (int s : score) {
			System.out.println(s);
		}

	}

}

 

 

  • 2차원 배열
public class TwoD {

	public static void main(String[] args) {
		
		int[][] arr = {
				{00,01,02,03},
				{10,11,12,13}
		};
		
		String[][] royal = new String[4][4];
		//royal[0][0] = "0층0호";
		System.out.println("층 : " + royal.length);
		System.out.println("호 : " + royal[0].length);
		
//		royal[0][1] = "0층1호";
//		royal[0][2] = "0층2호";
//		royal[0][3] = "0층3호";
//		royal[0][4] = "0층4호";
		
		for(int i=0; i<royal.length; i++) {	
			//System.out.println(i+"층");			
			for(int j=0; j<royal[i].length; j++) {
				//System.out.println(i+"층"+j+"호");
				royal[i][j] = i+"층"+j+"호" ;
				System.out.println(royal[i][j]);
			}
		}
		
		
		
	}

}

 

 

  • 3차원 배열
public class ThreeD {

	public static void main(String[] args) {
		//4개층 4개호 3개방

		String[][][] apt = new String[4][4][3];
		System.out.println("층 : "+apt.length);
		System.out.println("호 : "+apt[0].length);
		System.out.println("방 : "+apt[0][0].length);
		
		apt[2][3][2] = "철수의 방";
		apt[0][0][0] = "영희의 방";
		System.out.println(apt[0][0][1]);  //null  /  null != ""
		
		//"철수의 방"과 "영희의 방"을 제외한 나머지 방은 "공실"이라고 값을 넣는다.
		for(int i=0; i<apt.length; i++) {
			for(int j=0; j<apt[i].length; j++) {
				for(int k=0; k<apt[i][j].length; k++) {
					//System.out.println( i+"층"+j+"호"+k+"방");
					
					if(apt[i][j][k] == null) {
						apt[i][j][k] = "공실";
					}
					System.out.println(apt[i][j][k]);
					
					/*					
					if(i==0& j==0&k==0) {
						
					}else if(i==2& j==3&k==2) {
											
					}else {
						apt[i][j][k] = "공실" ;
					}
					System.out.println(apt[i][j][k]);
*/
				}
				
			}
			
		}

					
	}

}

 

 

 

 

Class(classification)

 

Classification(분류)

  • 가져온 부품을 잘 사용하기 위해서는 분류(classification)가 필요
  • Java는 class package라는 분류체계가 존재
  • Class : 각종 method와 변수 등을 담는 분류
  • Pacakage : 클래스들을 종류별로 담아놓은 폴더

 

OOP(Object Oriented Programming)

  • 객체들을 유기적으로 연결하여 프로그래밍 하는 것

 

OOP의 특징*(면접질문) - class의 특징

   : 남의 소스를 편리하게 사용

  1. 캡슐화(Encapsulation)
  2. 상속(Inheritance)
  3. 추상화(Abstractionism)
  4. 다형성(Polymorphism)

 

 

Class 선언

  • Java의 파일은 최소 1개 이상의 class를 가지고 있어야 한다.
  • class는 하나의 자료형이 될 수 있다. (String, Integer, Double, ...)  *자료형 : Data type
  • class 안에 class를 선언할 수도 있다.(잘 안씀)
  • class 생성 규칙
    1) 클래스의 첫 글자는 대문자
    2) $나 _외의 특수문자 사용X
    3) 클래스명파일명동일
    4) class의 이름은 어떤 변수와 함수의 종류를 대변하는 이름이어야 함(통용규칙)
package chap04.ex02.define;

public class Main {  //클래스
	
	// class -> 파스칼 표기법 : 첫글자가 대문자, 나머지는 소문자(Blackcolor)
	// 나머지 -> 카멜 표기법 : 첫글자 외에 의미를 갖는 단어를 대문자로 작성(blackColor)
	// 다른 언어들 -> 스내이크 표기법 : 의미를 갖는 단어 앞에 _로 구분(black_color)

	public static void main(String[] args) {  //매서드
		//main() 메서드가 없는 클래스는 스스로 동작할 수 없다.
		
		Student std = new Student();
		Student std2 = new Student();
		
		//std와 std2에 담긴 객체(instance)는 복사본이기 때문에 서로 다르다.
		System.out.println(std);
		System.out.println(std2);
		

	}

}
package chap04.ex02.define;

//학생과 관련된 메서드들이 있을 것이라 예상 가능
public class Student {
	//main 메서드가 없기 때문에 스스로 동작 불가능

}
  • class -> 파스칼 표기법 : 첫글자가 대문자, 나머지는 소문자(Blackcolor)
  • 나머지 -> 카멜 표기법 : 첫글자 외에 의미를 갖는 단어를 대문자로 작성(blackColor)
  • 다른 언어들 -> 스내이크 표기법 : 의미를 갖는 단어 앞에 _로 구분(black_color)

 

 

Class의 객체(instance)화

  • 원본 class를 복사해 오는 것(class : 원본, instance : 복사본)
  • Class의 특정 내용을 사용하기 위해서는 class를 객체화(instance) 해야 함
  • 복사된 객체는 변수에 담길 수 있음
  • 이때 데이터 타입은 객체의 원본 클래스 형태가 됨
package chap04.ex04.constr;

public class Main {

	public static void main(String[] args) {
		
		Robot robot = new Robot();

	}

}
package chap04.ex04.constr;

public class Robot {

	public Robot() { //생성자
		//클래스를 복사(객체화) 할 때 이녀석을 불러야 함
		//객체화 == 생성자 호출
		System.out.println("클래스를 복사합니다.");

	}

}

 

 

API(Application Programming Interface) : 객체의 기능을 사용하는 것 & 설명서

  • 응용프로그램에서 사용할 수 있도록, 운영체제나 프로그래밍 언어가 제공하는 기능을 제어 할 수 있게 만든 인터페이스

   *Interface : 실제로 하면 복잡한 일을 간단하게 할 수 있도록 만들어 놓은 어떤 장치

 

 

Java API

  • 어떤 일을 수행하기 위해 사용하는 도구방법(method) - 사용법도 포함되어 있음
  • oracle에서 제공하는 api 사이트를 이용 할 수 있지만 eclipse에서도 확인 가능

package chap04.ex03.myapi;

public class Main {

	public static void main(String[] args) {

		Calculator calc = new Calculator();
		int result = calc.plus(3, 4);
		System.out.println(result);

	}

}
package chap04.ex03.myapi;

public class Calculator {
	
	/**
	 * 이 메서드는 두 개의 정수를 넣으면 합하여 반환하는 매서드입니다.
	 * @param a 정수형태의 값
	 * @param b 정수 형태의 값
	 * @return a와 b를 더한 값
	 */
	int plus(int a, int b) {
		return a+b;
	}

}

 

 

Class의 member

  • constructor, field, method 가 있음

 

 

생성자(constructor)는 class객체화 

  • 객체화 시 constructor를 호출
  • Class가 instance 되면서 constructor가 가장 먼저 실행됨
  • 생성자는 객체화 될 때 초기화하는 수단으로 활용
  • 초기화는 0을 만드는 것이 아니고 최초의 값을 주는 것
package chap04.ex05.init;

public class Puppy {
	
	String name;
	String goal;

	public Puppy() {  //생성자
		
	}

	public Puppy(String name, String goal) {
		System.out.println(name + " / " + goal);
		this.name = name;
		this.goal = goal;
		
	}

}
package chap04.ex05.init;

public class Main {

	public static void main(String[] args) {
		
		Puppy p1 = new Puppy();
		//최초 생성 시 값을 줄 수 있다.
		Puppy p2 = new Puppy("멍멍이", "집지키기");
		System.out.println("이름 : " + p2.name);
		System.out.println("목적 : " + p2.goal);
		
		}
		
	}