Object-Oriented Programming (OOP)

Object − objects have states and behaviors.
Class – defines the grouping of data and code, the “type” of an object
Instance – a specific allocation of a class
Message – sent to objects to make them act
Method – a “function” that an object knows how to perform
Local Variables − variables defined inside methods, constructors or blocks
Instance Variables – variables within a class but outside any method (a specific piece of data belonging to an object)
Class Variables − variables declared within a class, outside any method, with the static keyword
Encapsulation – keep implementation private and seperate from interface
Polymorphism – different objects, same interface
Inheritance – hierarchical organization, share code, customize or extend behaviors

Lab2

Lab2 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서(3-4장정도 – 장수제한없음)를 넣고 JAVA20_Lab1_분반_학번_이름.zip 압축한 후 제출

java1-lab2

// https://www.ptable.com/?lang=ko
// number(int) symbol(String) name(String) weight(double)
// 1 H 수소 1.008
// 2 He 헬륨 4.0026
// 3 Li 리튬 6.94
// 4 Be 베릴륨 9.0122
// 5 B 붕소 10.81
// 6 C 탄소 12.011
// 7 N 질소 14.007
// 8 O 산소 15.999
// 9 F 플루오린 18.998
// 10 Ne 네온 20.180

Lab2 Basics (class, method, for, foreach, if, switch, do/while, while, array 활용)

Exceptions

ArrayIndexOutOfBoundsException 배열의 범위를 벗어난 접근할 때 발생

ArithmeticException 산술 연산 오류 에 의해 발생 (예를 들어, 0으로 정수를 나누는 경우)

NullPointerException null 객체를 사용하려고 시도할 때 발생

ClassCastException 변환할 수 없는 클래스로 객체 변환을 시도할 때 발생

NumberFormatException String을 숫자(number)로 변환할 수 없을 때 발생 (예를 들어, “1.23”을 Integer 변환을 시도할 때)

IllegalArgumentException 메소드 인자(argument) 유형을 잘못 사용할 경우

InputMismatchException (Scanner 클래스) 잘못된 입력일 때 발생

IOException 입출력(IO) 오류에 의해 발생

FileNotFoundException 지정된 경로에서 파일을 찾지 못할 때 발생

Break a loop if q-key is pressed

// break a loop if 'q'-key is pressed
static Scanner scan = new Scanner(System.in);
public static boolean getUserInputExitKey() {
    System.out.println("Please enter key to continue or the q-key to exit.");
    String input = scan.nextLine();
    if (input == null || input.contentEquals("")) return false;
    if (input.contentEquals("q")) return true;
    else return false;
}

//////////////////////////////////////////////////////////////////////////////////////////////

do {

// do whatever..

} while(!getUserInputExitKey());

returning an array from a method vs passing an array as parameter to a method

// returning an array from a method vs passing an array as parameter to a method

// passing an array as parameter to a method
public static int sumArray(int[] arr) {
	int sum = 0;
	for (int i = 0; i < arr.length; i++) {
		sum += arr[i];		
	}
	return sum;
}

// returning an array from a method
public static int[] assignArray(int length) {
	int[] arr = new int[length];
	for (int i = 0; i < arr.length; i++) {
		arr[i] = i;
	}
	return arr;
}

////////////////////////////////////// in main
// returning an array from a method
int[] arr1 = assignArray(3);
int[] arr2 = assignArray(5);
for (int e : arr1)	System.out.println(e); // 0 1 2
for (int e : arr2)	System.out.println(e); // 0 1 2 3 4

// passing an array as parameter to a method
int[] array1 = {100, 200, 300};
int[] array2 = {50, 60, 70, 80, 90};
int sum1 = sumArray(array1);
int sum2 = sumArray(array2);
System.out.println("array1 sum=" + sum1); // 100 + 200 + 300 = 600
System.out.println("array2 sum=" + sum2); // 50 + 60 + 70 + 80 + 90 = 350

2D Array

// 2D array
char[] ops = {'+', '-', '*', '/'};
int[][] numbers = {{60,50}, {40,30}, {20,10}};
for (char op : ops) {
    for (int i = 0; i < numbers.length; i++) {
        int result = calc(numbers[i][0], numbers[i][1], op);
        System.out.printf("result = %d %s %d = %d\n", numbers[i][0], op, numbers[i][1], result);
    }
}

result = 60 + 50 = 110
result = 40 + 30 = 70
result = 20 + 10 = 30
result = 60 – 50 = 10
result = 40 – 30 = 10
result = 20 – 10 = 10
result = 60 * 50 = 3000
result = 40 * 30 = 1200
result = 20 * 10 = 200
result = 60 / 50 = 1
result = 40 / 30 = 1
result = 20 / 10 = 2

Person Array

Person[] pArray = new Person[5];
// 만약 Person 객체를 하나만 생성한 후 for문에서 공유해 사용할 경우
// 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
Person p = new Person();
for (int i = 0; i < 5; i++) {
    System.out.print("\n\nEnter Person name : ");
    Scanner input = new Scanner(System.in);
    p.setName(input.nextLine()); // 입력정보
    System.out.print("\n\nEnter Person age [int] : ");
    p.setAge(input.nextInt()); // 입력정보
    p.print();
    pArray[i] = p; // 리스트에 들어간 모든 원소는 동일한 p
}
System.out.println("pArray : " + Arrays.toString(pArray));

Person[] pArray = new Person[5];
// 아래와 같이 for문 안에 Person p = new Person()와같이
// 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 5; i++) {
    Person p = new Person();
    System.out.print("\n\nEnter Person name : ");
    Scanner input = new Scanner(System.in);
    p.setName(input.nextLine()); // 입력정보
    System.out.print("\n\nEnter Person age [int] : ");
    p.setAge(input.nextInt()); // 입력정보
    p.print();
    pArray[i] = p; // 이때 p는 새로운 Person객체
}
System.out.println("pArray2 : " + Arrays.toString(pArray2));