전공 과목 이수2👨‍💻/JAVA(공)

자바| 1장~6장실습 / 연습문제

천숭이 2021. 4. 28. 23:57

java.io 클래스를 임포트한다

-> ioexception, bufferedreader 함수 사용가능

 

문자형태를 정수형태로 변경가능하다. 따라서 10이상의 숫자도 받아서 저장할 수 있음. (한 라인)

package soobin;

//import java.io.BufferedReader;
//import java.io.IOException;
import java.io.*;

public class Test1 {
	public static void main(String[] args) throws java.io.IOException {
		int n;
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		n=Integer.parseInt(input.readLine());
		System.out.println(n)	;
		System.out.println(n-1);
	}
	
}

 

 


 

1장 예제

예제 1.4

public class Primitives {
	public static void main(String[] args) {
		boolean b;
		int i = Integer.MAX_VALUE;
		double d = Double.MIN_VALUE;
		b = ( i != 0 );
		System.out.println("boolean b = " + b);
		System.out.println("max value of integer = " + i);
		System.out.println("min value of double = " + d);
	}
}

결과:

boolean b = true
max value of integer = 2147483647
min value of double = 4.9E-324

 

예제 1.5

public class ShiftExample {
	public static void main(String[] args) {
		int i = -1;
		int x = i >>> 1;
		int y = i >> 1;
		System.out.println("-1 >>> 1 = " + x);
		System.out.println("-1 >> 1 = " + y);
	}
}

결과 :

-1 >>> 1 = 2147483647
-1 >> 1 = -1

 

예제 1.6 - 문자열 생성 두가지 방법

public class StringExample {
	public static void main(String[] args) {
		String hello = "Hello";
		String world = new String("World");
		System.out.println(hello + world + "!");
	}
}

예제 1.7 - 스택을 범용 클래스로 정의한 후 정수형 스택과 실수형 스택을 생성하여 사용하는 방법을 보여주는 예제

(***스택 오버플로, 언더플로를 검사하는 부분 추가해보기)

class Stack<StackType> {
	private StackType[] stack = (StackType[]) new Object[100];
	private int sp = -1;
	public void push(StackType element) {
		stack[++sp] = element;
	}
	public StackType pop() {
		return stack[sp--];
	}
}

public class GenericClassExample {
	public static void main(String[] args) {
		Stack<Integer> stk1 = new Stack<Integer>(); // 정수형 스택
		Stack<Double> stk2 = new Stack<Double>(); // 실수형 스택
		stk1.push(1); stk1.push(2); stk1.push(3);
		System.out.println("integer stack : " + stk1.pop() + " " + stk1.pop() + " " + stk1.pop());
		stk2.push(1.5); stk2.push(2.5); stk2.push(3.5);
		System.out.println("double stack : " + stk2.pop() + " " +stk2.pop() + " " + stk2.pop());
	}
}

결과 :

integer stack : 3 2 1
double stack : 3.5 2.5 1.5

 

예제 1.8 - try블록안에서 예외가 검사하고 예외가 발생하면 catch블록에서 예외가 처리. finally는 어떤 경우든 반드시 실행되는 블록

public class ExceptionExample {
	public static void main(String[] args) {
		try {
			System.out.println("Exception throwing...");
			throw new Exception();
		} catch (Exception e) {
			System.out.println("Caught Exception");
		} finally {
			System.out.println("In the finally statement...");
		}
	}
}	

Exception throwing...
Caught Exception
In the finally statement...

 

예제1.9 

class ExtnOfThread extends Thread {
	public void run() {
		System.out.println("Extension of Thread, 1");
		try {
			sleep(1000);
		} catch (InterruptedException ie) { }
		System.out.println("Extension of Thread, 2");
	}
}
class ImplOfRunnable implements Runnable {
	public void run() {
		System.out.println("Implementation of Runnable");
	}
}
public class ThreadExample {
	public static void main(String[] args) {
		ExtnOfThread t1 = new ExtnOfThread();
		t1.start();
		Thread t2 = new Thread (new ImplOfRunnable());
		t2.start();
	}
}

Extension of Thread, 1
Implementation of Runnable
Extension of Thread, 2

 


2장 예제

 

예제2.3 - 실수형상수의 묵시적인 형은 double이다 float형으로 만들려면 뒤에 f또는 F를 붙이면된다

public class RealConstant {
	public static void main(String[] args) {
		float f1=1.414F, f2=0.1414e01f;
		double d=0.1414E1;
		System.out.println("f1 = " + f1 + ", f2 = " + f2 + ", d = " + d);
		if (f1 == f2) System.out.println("Yes");
		else System.out.println("No");
		if (f2 == d) System.out.println("Yes");
		else System.out.println("No");
	}
}

f1 = 1.414, f2 = 1.414, d = 1.414
Yes
No

 

예제 2.5 - 스트링리터럴. 자바에서 스트링 리터럴은 java.lang.String클래스의 객체로 취급된다.

public class CharString {
	public static void main(String[] args) {
		char c = 'A'; // 'A' <=> 65
		int i;
		i = c + 1;
		System.out.println("c = " + c + "\ni = " + i+","+(char)i);
		System.out.println("\"I am a string.\"");
	}
}

c = A
i = 66,B
"I am a string."

 

예제 2.8 - 배열에 값 저장 (배열의 크기는 배열.length)

public class ArrayType {
	public static void main(String[] args) {
		int[] ia = new int[3];
		int ib[] = { 1, 2, 3 };
		int i;
		for (i = 0; i < ia.length; i++)
		ia[i] = ib[i];
		for (i = 0; i < ia.length; i++)
		System.out.print(ia[i] + " ");
		System.out.println();  // 1 2 3 출력
	}
}

 

예제 2.9 - 이중배열,다차원 배열(배열의 배열)

public class ArrayOfArray {
	public static void main(String[] args) {
		int[][] matrix = new int[3][]; // declaration, 행만먼저 설정가능
		int i, j;
		for (i = 0; i < matrix.length; i++) // creation
			matrix[i] = new int[i+3]; // [3개], [4개], [5개]로 배열크기설정
		for (i = 0; i < matrix.length; i++) // using
			for (j = 0; j < matrix[i].length; j++)
				matrix[i][j] = i*matrix[i].length + j;
		for (i = 0; i < matrix.length; i++) { // printing
			for (j = 0; j <matrix[i].length; j++)
				System.out.print(" " + matrix[i][j]);
			System.out.println();
		}
	}
}

 0 1 2
 4 5 6 7
 10 11 12 13 14

 

예제2.10 - 열거형은 서로 관련있는 상수들의 모음. 0부터 순서값 가짐. Enum열거형을 기반으로 한 클래스형 선언.

values() : 열거된 모든 원소를 순서대로 반환하는 메소드

ordinal() : 원소의 열거된 순서를 정수 값으로 반환하는 메소드

valueOf() : 매개변수로 주어진 스트링과 열거형에서 일치하는 이름 갖는 원소를 반환하는 메소드. 원소가 없는 경우의 예외는 IllegalArgumentException 발생

enum Color { Red, Green, Blue, Yellow }
public class EnumTypeExample {
	public static void main(String[] args) {
		for (Color col : Color.values()) {
			System.out.println(col);
		}
		Color c = Color.Red;
		System.out.println(c + "'s value is " + c.ordinal());
		c = Color.valueOf("Blue");
		System.out.println(c + "'s value is " + c.ordinal());
		c = Color.valueOf("Yellow");
		System.out.println(c + "'s value is " + c.ordinal());
			}
	}
	

Red
Green
Blue
Yellow
Red's value is 0
Blue's value is 2
Yellow's value is 3

 

예제 2.11 - week요일 열거형의 우너소는 순서값가 더불어 특정한 값을 가지고 있다.

enum Week {
	Sunday(0), Monday(1), Tuesday(2), Wednesday(4),
	Thursday(8), Friday(16), Saturday(1004);
	private final int value;
	Week(int value) { this.value = value; }
	public int value() { return value; }
}
public class PredefinedValueEnumTypeExample {
	public static void main(String[] args) {
		for (Week w : Week.values()) {
			System.out.println(w + ": ordinal=" + w.ordinal() + ", value=" + w.value());
		}
	}
}

Sunday: ordinal=0, value=0
Monday: ordinal=1, value=1
Tuesday: ordinal=2, value=2
Wednesday: ordinal=3, value=4
Thursday: ordinal=4, value=8
Friday: ordinal=5, value=16
Saturday: ordinal=6, value=1004


2장연습문제

 

문제2.7 - 행과열을바꾼느 메소드 transpose(전치)를 작성

package quiz;

public class Quiz_2_8 {
	public static void Transpose(int arr1[][], int arr2[][]) {
		for (int i=0;i<arr1.length;i++) {
			for(int j=0;j<arr1[0].length;j++) {
				arr2[j][i]=arr1[i][j];
			}
		}
	}
	public static void PrintMatrix(int arr[][]) {
		for (int i=0;i<arr.length;i++) {
			for (int j=0;j<arr[0].length;j++) {
				System.out.print(arr[i][j]+" ");
			}
			System.out.println();
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int arr1[][]= {{1,2,3},{4,5,6}};
		// 오리지널 행렬은 2행 3열
		
		System.out.println("배열크기확인 :"+arr1.length+" "+arr1[0].length);
		PrintMatrix(arr1);
		
		int[][] arr2=new int [arr1[0].length][arr1.length];
		// 전치되는 행렬은 3행 2열로
		
		Transpose(arr1,arr2);
		
		PrintMatrix(arr2);
	}

}

배열크기확인 :2 3
1 2 3 
4 5 6 

1 4 
2 5 
3 6 

 

문제2.8 - 마방진을 구성하는 프로그램. 가로,세로,대각선에 있는 수들의 합이 모두 같은 정방형 매트릭스

public class ExerciseCh2_8 {
	public static void main(String[] args) throws java.io.IOException{
		int n = System.in.read() - '0';
		int [][] matrix = new int [n][n];
		int number, row, col, row_b, col_b;
		
		for(row=0; row<n; row++)
			for(col=0; col<n;col++)
				matrix[row][col] = 0;
		
		// 값 초기화
		row = 0;
		col = n/2;
		number = 1;
		matrix[row][col] = number; //[0][1]에 1넣음, [0][2]에 1넣음
		
		while(number<=n*n) {
			matrix[row][col] = number;
			
			row_b = row;
			col_b = col;
			col++;
			row--;
			
			if(row < 0) //row가 -1
				row = row % n + n;
			if(col > n-1) //col이 n
				col = col % n;
			if(matrix[row][col]!=0) //이미 숫자가 있으면 밑에다 적음
			{
				row = row_b+1;
				col = col_b;
			}
			number++;
		}
		for(row=0; row<n; row++)
		{
			for(col=0; col<n;col++)
				System.out.print(matrix[row][col]);
			System.out.println();
		}
	}

}

입력 : 3
8 1 6 
3 5 7 
4 9 2 

 

입력 : 5

17 24 1 8 15 
23 5 7 14 16 
4 6 13 20 22 
10 12 19 21 3 
11 18 25 2 9 

 

문제2.10 - 16진수를 10진수로 변환하는 프로그램

public class chp2_10 {
	static int hexValue(char ch) {
		switch(ch) {
		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			return (ch - '0');
		case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
			return (ch - 'A' + 10);
		case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
			return (ch - 'a' + 10);
		default: return -1;
		}
	}
	public static void main(String[] args) throws java.io.IOException{
		int num = 0;
		int value;
		char ch;
			
		ch = (char) System.in.read();
		if (ch == '0') {
			ch = (char) System.in.read();
			if((ch == 'X')||(ch == 'x'))
				while ((value=hexValue(ch=(char) System.in.read()))!= -1)
					num = 16*num + value;
			else if((ch >= '0') && (ch <= '7'))
				do { num = 8*num + (int)(ch - '0');
					ch = (char) System.in.read();
				}while((ch >= '0') && (ch <= '7'));
			else num = 0;
		}else do { num = 10*num + (int)(ch - '0');
					ch = (char) System.in.read();
			}while (Character.isDigit(ch));
		System.out.println(num);
	}
}

입력 : 0x45

69

 


3장연습문제

 

문제3.8 - 입력문자가 대문자이면 소문자로 변경해서 출력, 소문자이면 대문자로 변경해서 출력

package quiz;

public class Quiz_3_8 {
	public static void main(String[] args) throws java.io.IOException{
		char c;
		
		System.out.print("Enter a character = ");
		c = (char) System.in.read();
		if(c >= 'A' && c <= 'Z') c += ('a' - 'A'); // 대문자입력일때
		else if (c >= 'a' && c <= 'z') c += ('A' - 'a'); // 소문자입력일때
		System.out.println("Converted character = " + c);
	}
}

문제3.9 (2)

package quiz;

public class Quiz_3_9 {
	public static void main(String[] args) {
		double x=Double.MAX_VALUE, y=Double.NEGATIVE_INFINITY;
		System.out.println(x/y);
		System.out.println(y-y);
		System.out.println(x/0.0);
	}
}

-0.0
NaN
Infinity

 

문제3.9 (3) - 비트수를 세서 출력

package quiz;

public class Quiz_3_9_3 {
	public static void main(String[] args) {
		System.out.println("number of bits = " + f(037));
	}
	public static int f(int n) {			// 1의 비트 수를 세는 메소드
		int m;
		for (m=0; n!=0; n>>=1)
			if((n & 1) == 1) m++;
		return m;
	}
}

number of bits = 5

 

문제 3.10 - 삼각형의 세변의 길이를 읽고 다음 공식에 의해 삼각형의 넓이를 구하는 프로그램
(한줄로 입력받음)

package quiz;

import java.io.IOException;

public class Quiz_3_10_1 {

	public static void main(String[] args) throws IOException {
		int a,b,c;
		a=System.in.read()-'0';
		b=System.in.read()-'0';
		c=System.in.read()-'0';
		
		double l = (a+b+c)/2.0;
		double s = Math.sqrt(l*(l-a)*(l-b)*(l-c));
		
		System.out.println(s);
	}
}

입력: 345

6

 

문제 3.10.(3) - 원금과 이율 기간을 입력받아 복리법에 의해 원리합계 구하는 프로그램

(문장 단위로 입력받기)

package quiz;

import java.io.*;

public class Quiz_3_10_3 {
	public static void main(String[] args) throws java.io.IOException{
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		double money, rate, day;
		
		money = Double.parseDouble(input.readLine());
		rate = Double.parseDouble(input.readLine());
		day = Double.parseDouble(input.readLine());
	
		double S = money * Math.pow(1+rate, day);
		System.out.println(S);
	}
}

입력1: 500000
입력2: 0.2
입력3: 10
3095868.211199999

 

문제3.10 섭씨온도값, 수학연산, 비만도 계산, 직렬병렬 연결, 반지름 입력받고 공의 부피와 표면적 구하기~~

 

문제3.10.(8) - 연도를 읽어 윤년인지를 판별하기

package quiz;

import java.io.*;

public class Quiz_3_10_8 {
	public static void main(String[] args) throws java.io.IOException{
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		double year;
		
		year = Double.parseDouble(input.readLine());

		if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
			System.out.println("윤년입니다.");
		else
			System.out.println("윤년이 아닙니다.");
	}
}

입력 : 2020

윤년입니다.

 


4장 예제

예제4.2 - 한자리수 숫자받아서 제곱과 세제곱 출력하기. char로 읽고 '0'을 뺀다

package quiz;

import java.io.IOException;

public class CompoundSt_4_2 {

	public static void main(String[] args) throws java.io.IOException {
		int n;
		System.out.println("Enter one digit = ");
		n=System.in.read()-'0';
		if (n<0)
			System.out.println("Negative number!");
		else {
			System.out.println(n+" squard is "+(n*n));
			System.out.println(n+" cubed is "+(n*n*n));
		}
	}
}

 

예제4.5 - 숫자 입력받고 홀짝수 판별하기

public class IfSt {
	public static void main(String[] args) throws java.io.IOException {
		int n;
		System.out.print("Enter a number = ");
		n = System.in.read() - '0';
		if (n % 2 == 0) System.out.println(n + " is an even number.");
		else (n % 2 != 0) System.out.println(n + " is an odd number.");
	}
}

Enter a number = 8
8 is an even number.

 

예제 4.12 - 자바에서만 쓸 수 있는 반복문 형태

public class EnhancedForSt {
	public static void main(String[] args) {
		String[] color = { "red", "green", "blue" };
		for (String s: color) {
			System.out.println(s);
		}
	}
}

red
green
blue

 

system.in.read()는 하나의 문자를 읽어서 코드 값으로 리턴해주기 때문에 숫자인 경우에는 반드시 문자 '0'의 코드 값인 48을 빼야 해당하는 숫자 값이 된다.
system.in.read()메소드를 이용해 표줌 입력으로부터 하나의 정수 상수를 읽어드이는 메소드를 작성할 수 있다.
isDigit()메소드는 Character클래스에 정의되어 있는 메소드로 숫자인가를 판별해주는 메소드. #숫자판별메소드



4장예제

 

문제4.8 (1) - 100이하의 소수를 구하는 프로그램

package quiz;

public class Quiz_4_8 {
	public static void main(String[] args) {
		int i,j;
		
		for(i=1;i<=100;i++) {
			for(j=2;j<=i;j++) {
				if(i%j==0)
					break;
			}
			if(j==i)
				System.out.print(i + " ");
		}
	}
}

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

 

문제4.8 (2) - 완전수(자기자신을제외한 약수의 합이 자기 자신과 같은 수)

package quiz;

public class Quiz_4_8 {
	public static void main(String[] args) {
		for (int i=1;i<500;i++) {
			int cnt=0;
			for (int j=1;j<i;j++) {
				if (i%j==0) {
					cnt += j;
				}
			}
			if (cnt == i) System.out.print(i+" ");
		}
	}
}

6 28 496 

 

문제4.8(3) - 회문수란 숫자를 역순으로 쓴 수와 같은 수를 말한다. int형으로 입력받는다(한자리수 이상 수들도 받을 수 잇음*****)

package quiz;

import java.io.*;

public class Quiz_4_8 {
	public static void main(String[] args) throws java.io.IOException{
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		int num, n;
		int m=0;
		
		n = Integer.parseInt(input.readLine());
		num = n;
		
		while(n!=0) {
			m = m*10 + n%10;
			System.out.println("m : "+m);
			n = n/10;
			System.out.println("n : "+n);
		}
		if(num==m)
			System.out.print("회문수 입니다.");
		else
			System.out.print("회문수가 아닙니다.");
	}
}

12345
m : 5
n : 1234
m : 54
n : 123
m : 543
n : 12
m : 5432
n : 1
m : 54321
n : 0
회문수가 아닙니다.

 

문제4.8(4) - 암스트롱수 각 자릿수의 수 세제곱의 합이 자신과 같은 수

package quiz;

import java.io.*;

public class Quiz_4_8 {
	public static void main(String[] args) {
		int i,n,sum;
		
		for(i=100; i<500; i++) {
			n=i;
			sum=0;
			while(n!=0) {
				sum += Math.pow(n%10, 3);
				n = n/10;
			}
			if(sum == i)
				System.out.print(i + " ");
		}
	}
}

153 370 371 407 

 

문제4.8(5) - 최대공약수와 최소공배수구하기

import java.io.*;
public class Quiz_4_8 {
	static int gcd(int n, int m) {
		while(n!=m)
			if(n>m) n-=m;
			else m-=n;
		return n;
	}
	public static void main(String[] args) throws java.io.IOException{
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		int n,m;
		
		n = Integer.parseInt(input.readLine());
		m = Integer.parseInt(input.readLine());
		
		int gcd = gcd(n,m);
		int lcd = (m/gcd) * (n/gcd) * gcd;
		
		System.out.println("gcd = " + gcd);
		System.out.println("lcd = " + lcd);
	}
}

 

문제4.8(8) - 구구단 출력 프로그램

package quiz;

import java.io.*;

public class Quiz_4_8 {
	public static void main(String[] args) {
		int i,j;
		
		for(i=1;i<=9;i++) {
			for(j=2;j<=9;j++) {
				System.out.print(j + " * " + i + " = " + j*i + ",\t");
			}System.out.println();
		}
	}
}

 

문제4.8(9) 숫자웨이브 (p.174) 4장 연습문제 파일 참고

 

강의 예제 4.9- 연산기호,숫자두개받아서 계산기 프로그램

package exercise;

import java.io.IOException;

public class SwitchSt2_4_9 {

	public static void main(String[] args) throws IOException {
		int x,y,p=0;
		char c;
		System.out.println("Enter the operator & two number =");
		c=(char) System.in.read();
		x=(int) System.in.read()-'0';
		y=(int) System.in.read()-'0';
		
		switch(c) {
		case '+' : {
			p=x+y;
			System.out.println(x+" + "+ y+" = "+p);
		}break;
		case '-' : {
			p=x+y;
			System.out.println(x+"-"+y+"="+p);
		}break;
		case '*' : {
			p=x*y;
			System.out.println(x+" * "+y+" = "+p);
		}break;
		default : System.out.println("Illegal operator");
		}
	}
}

Enter the operator & two number =
*98
9 * 8 = 72


5장예제

 

예제 5.2 - 분수 toString()메소드 이용해 출력하기

class Fraction {
	int numerator; // 분자
	int denominator; // 분모
	Fraction(int num, int denom) { // 생성자
		numerator = num;
		denominator = denom;
	}
	public String toString() {String form = numerator + "/" + denominator;
	return form;
	}
}
public class ExampleOftoString {
	public static void main(String[] args) {
		Fraction f = new Fraction(1,2);
		System.out.println("Implicit call = " + f);
		System.out.println("Explicit call = " + f.toString());
	}
}

Implicit call = 1/2
Explicit call = 1/2

 

정적 메소드 호출 형태 :
ClassName.methodName;
객체생성하지 않고 함수명으로 바로 호출가능

예제5.3 - 정적함수 선언 및 호출, 활용형태 (# static)

class Count {
	public static int scount = 0;
	public int count = 0;
	public static void sIncrement() {
		scount++;
	}
	public void increment() {
	count++;
	}
}
public class StaticMethod {
	public static void main(String[] args) {
		Count c = new Count();
		Count d = new Count();
		c.increment(); Count.sIncrement();
		d.increment(); d.sIncrement();
	
		System.out.print("Instance Value: c.count = " + c.count );
		System.out.println(", Static Value: c.scount = " + c.scount);
		System.out.print("Instance Value: d.count = " + d.count);
		System.out.println(", Static Value: Count.scount = " + Count.scount);
		System.out.println("Shared Value ? " + ( c.scount == d.scount));
	}
}

Instance Value: c.count = 1, Static Value: c.scount = 2

Instance Value: d.count = 1, Static Value: Count.scount = 2

Shared Value ? true

 

예제5.4 - call by value 값호출

매개변수 전달방법은 값호출이며 실 매개변수의 값이 형식매개변수로 전달된다. 따라서, 메소드 내에서 매개변수의 값을 변경해도 변경된 값이 매개변수를 통해 다시 호출한 곳으로 넘겨질 수는 없다.

public class CallByValue {
	public static void swap(int x, int y) {
		int temp;
		temp = x; x = y; y = temp;
		System.out.println(" swap: x = " + x + ", y = " + y);
	}
	public static void main(String[] args) {
		int x = 1, y = 2;
		System.out.println("before: x = " + x + ", y = " + y);
		swap(x, y);
		System.out.println(" after: x = " + x + ", y = " + y);
	}
}

before: x = 1, y = 2
swap: x = 2, y = 1
after: x = 1, y = 2

(변경 실패)

 

예제 5.5 (5.4보완) - 객체의 참조를 매개변수로 사용해야 한다.

class Swap {
	public int x, y;
	public static void swap(Swap obj) {
		int temp;
		temp = obj.x; obj.x = obj.y; obj.y = temp;
		System.out.println(" swap: x = " + obj.x + ", y = " + obj.y);
	}
}
public class CallByReference {
	public static void main(String[] args) {
		Swap a = new Swap();
		a.x = 1; a.y = 2;
		System.out.println("before: x = " + a.x + ", y = " + a.y);
		Swap.swap(a);
		System.out.println(" after: x = " + a.x + ", y = " + a.y);
	}
}

before: x = 1, y = 2
 swap: x = 2, y = 1
 after: x = 1, y = 2

 

예제5.6 - #가변배개변수 실매개변수의 개수가 상황에 따라 가변적인 경우가 발생한다. 

형식 : void VarArgs1(int... args) 자료형과 매개변수 사이에 ...을 기술하는 것

public class VarArgs {
	public static void methodWithVarArgs(Object... args) {
		System.out.println("Variable Argument Example");
		for (Object x: args)  // ***
		System.out.println(x);
	}
	public static void methodWithIntVarArgs(String s, int... args) {
		System.out.println("Integer Variable Argument Example");
		int sum = 0;
		for (int i: args)   // ***
		sum += i;
		System.out.println(s + sum);
	}
	public static void main(String[] args) {
		methodWithVarArgs(10.0, 20.0, 30.0, 40, 50);
		methodWithIntVarArgs("Total is ", 10, 20, 30, 40, 50);
	}
}

Variable Argument Example
10.0
20.0
30.0
40
50
Integer Variable Argument Example
Total is 150

 

예제 5.8 - 메소드중복 (overriding), 메소드 이름은 같은데 매개변수의 개수와 형이 다른 경우를 메소드가 중복되었다고 말한다.

public class MethodOverloading {
	void someThing() {
		System.out.println("someThing() is called.");
	}
	void someThing(int i) {
		System.out.println("someThing(int) is called.");
	}
	void someThing(int i, int j) {
		System.out.println("someThing(int,int) is called.");
	}
	public static void main(String[] args) {
		MethodOverloading m = new MethodOverloading();
		m.someThing();
		m.someThing(526);
		m.someThing(54, 526);
	}
}

someThing() is called.
someThing(int) is called.
someThing(int,int) is called.

 

예제 5.10 - 분수 (분모필드, 분자필드) 분자분모별로 받아서 생성자 총 세개

class Fraction {
	int numerator; // 분자 필드
	int denominator; // 분모 필드
	Fraction() { // 디폴트 생성자
		numerator = 0;
		denominator = 1;
	}
	Fraction(int num) { // 생성자
		numerator = num;
		denominator = 1;
	}
	Fraction(int num, int denom) { // 생성자
		numerator = num;
		denominator = denom;
	}
	public String toString() {
		String form = numerator + "/" + denominator;
		return form;
	}
}
public class OverloadedConstructor {
	public static void main(String[] args) {
		Fraction f1 = new Fraction();
		Fraction f2 = new Fraction(2);
		Fraction f3 = new Fraction(1,2);
		System.out.println("f1 = " + f1 + ", f2 = " + f2 + ", f3 = " + f3);
	}
}

f1 = 0/1, f2 = 2/1, f3 = 1/2

 

예제 5.12 this()연산자 사용

 

예제 5.13 정적초기화문은 생성자보다 더 빨리 실행된다.

 

예제 5.15 - 중첩클래스를 내부와 외부에서 사용하는 예

class OuterClass {
	class InnerClass {
		private int value;
		InnerClass(int i) {
			value = i;
		}
		void print() {
			System.out.println("value of Inner class = " + value);
		}
	} // end of InnerClass
	public void link(int i) {
		InnerClass inObj = new InnerClass(i);
		inObj.print();
	}
} // end of OuterClass
public class NestedClass {
	public static void main(String[] args) {
		OuterClass outObj = new OuterClass();
		outObj.link(1);
		OuterClass.InnerClass inObj = outObj.new InnerClass(2);
		inObj.print();
	}
}

value of Inner class = 1
value of Inner class = 2

 

예제 5.19 - 분수형을 위한 클래스 정의하기

class Fraction {
	private int numerator; // 분자
	private int denominator; // 분모
	Fraction(int num, int denom) { // 생성자
		numerator = num;
		denominator = denom;
	}
	private int gcd(int x, int y) { // 최대 공약수를 구하는 메소드
		return (y!=0) ? gcd(y, x%y) : x;
	}
	private Fraction reduce(Fraction f) { // 기약 분수로 만드는 메소드
		int divisor;
		divisor = gcd(f.numerator, f.denominator);
		f.numerator = f.numerator / divisor;
		f.denominator = f.denominator / divisor;
		return f;
	}
	public Fraction add(Fraction f) {
		numerator = numerator * f.denominator + f.numerator * denominator;
		denominator = denominator * f.denominator;
		return reduce(this);
	}
	public Fraction mul(Fraction f) {
		numerator = numerator * f.numerator;
		denominator = denominator * f.denominator;
		return reduce(this);
	}
	public String toString() {
		String form = numerator + "/" + denominator;
		return form;
	}
}
public class FractionTest {
	public static void main(String[] args) {
		Fraction f1 = new Fraction(1, 2);
		Fraction f2 = new Fraction(3, 4);
		f1 = f1.add(f2);
		f2 = f2.mul(f1);
		System.out.println("f1 = " + f1 + ", f2 = " + f2);
	}
}

f1 = 5/4, f2 = 15/16

 

5장 연습문제

문제 5.7 - 복소수

package quiz;

class Complex{
	public double real;
	public double image;
	Complex(double r, double i){
		real = r;
		image = i;
	}
	
	public Complex addComplex(Complex c) {
		Complex c0 = new Complex(0,0);
		c0.real = real + c.real;
		c0.image = image + c.image;
		return c0;
	}
	
	public Complex subComplex(Complex c) {
		Complex c0 = new Complex(0,0);
		c0.real = real - c.real;
		c0.image = image - c.image;
		return c0;
	}
	
	public Complex mulComplex(Complex c) {
		Complex c0 = new Complex(0,0);
		c0.real = real * c.real - image * c.image;
		c0.image = real * c.image + image * c.real;
		return c0;
	}
	
	public Complex divComple(Complex c) {
		Complex c0 = new Complex(0,0);
		c0.real = (real * c.real + image * c.image) /
		(c.real * c.real + c.image * c.image);
		c0.image = (image * c.real - real * c.image) /
		(c.real * c.real + c.image * c.image);
		return c0;
	}
	public String toString() {
		String form = "(" + real + ", " + image + "i)";
		return form;
	}
}

public class Quiz_5_7 {
	public static void main(String[] args) {
		Complex c1 = new Complex(1,2);
		Complex c2 = new Complex(3,4);
		Complex c3 = new Complex(5,6);
		Complex c4 = new Complex(7,8);
		c1 = c1.addComplex(c2);
		c2 = c2.subComplex(c3);
		c3 = c3.mulComplex(c4);
		c4 = c4.divComple(c1);
		System.out .print("c1 = " + c1 + ", c2 = " + c2 +
		", c3 = " + c3 + ", c4 = " + c4);
	}
}

 

예제 5.8 - 스택을 배열로 사용하여 구현

package quiz;

import java.io.*;

class Stack{
	private int stack[];
	int sp = -1;
	Stack(){
	stack = new int[100];
	}
	Stack(int size){
	stack = new int[size];
	}
	public void push(int data) {
		if(stack.length == sp+1)
		System.out .println("스택이 가득 찼습니다.");
		
		else {
		stack[++sp] = data;
		}
	}
	
	public int pop() {
		if(sp == -1) {
			System.out .println("스택이 비었습니다.");
			return 0;
		}
		return stack[sp--];
		}
		public int size() {
			return sp;
		}
	}

public class Quiz_5_8 {
	public static void main(String[] args) throws java.io.IOException{
	BufferedReader input = new BufferedReader(new InputStreamReader(System.in ));
	Stack s = new Stack(3);
	int a = -1;
	s.pop();
	while(a!=0) {
		a = Integer.parseInt (input.readLine());
		s.push(a);
	}
	while(s.size() >= 0)
		System.out .println(s.pop());
	}
}

 


6장 예제

예제 6.2 - 서브클래스는 슈퍼클래스의 모든 필드들을 갖고 있기 때문에 서브클래스의 생성자에서는 먼저 슈퍼클래스의 생성자를 호출해야 한다. 만일 서브클래서에서 명시적으로 슈퍼클래스의 생성자를 호출하지 않으면 컴파일러에 의해 내부적으로 호출됨.

class SuperClass {
	SuperClass() {
		System.out.println("SuperClass Constructor ...");
	}
}
class SubClass extends SuperClass {
	SubClass() {
		System.out.println("SubClass Constructor ...");
	}
}
public class SubConstructor {
	public static void main(String[] args) {
		SubClass obj = new SubClass();
		System.out.println("in main ...");
	}
}

SuperClass Constructor ...
SubClass Constructor ...
in main ...

 

예제 6.3 - 슈퍼클래스의 중복된 생성자 호출

class SuperClass {
	int a, b;
	SuperClass() {
		a = 1; b = 1;
	}
	SuperClass(int a, int b) {
		this.a = a; this.b = b;
	}
}
class SubClass extends SuperClass {
	int c;
	SubClass () {
		c = 1;
	}
	SubClass (int a, int b, int c) {
		super(a, b);
		this.c = c;
	}
}
public class SuperCallTest {
	public static void main(String[] args) {
		SubClass obj1 = new SubClass();
		SubClass obj2 = new SubClass(1,2,3);
		System.out.println("a = " + obj1.a + ", b = " + obj1.b +
		", c = " + obj1.c);
		System.out.println("a = " + obj2.a + ", b = " + obj2.b +
		", c = " + obj2.c);
	}
}

a = 1, b = 1, c = 1
a = 1, b = 2, c = 3