본문 바로가기

Language/JAVA

[JAVA] 명품 자바 에센셜 예제 6장

 

예제 6-1 : Object 클래스로 객체 속성 알아내기
문제: Object 클래스를 이용하여 객체의 클래스명, 해시 코드 값, 객체의 문자열을 출력해보자.

package chap06;
//package chap06_assign;

 class Point{
	private int x,y;
	public Point(int x, int y) {
		this.x=x; this.y=y;
	}
}

public class ObjectPropertyEx {
	public static void main(String[] args) {
		Point p = new Point(2,3);
		System.out.println(p.getClass().getName()); //클래스 이름
		System.out.println(p.hashCode());	//해시 코드 값
		System.out.println(p.toString());	//객체의 문자열
	}

}
//출력결과
Point
22279806
Point@153f67e

 

예제 6-2 : Point 클래스에 toString()작성
문제:Point클래스에 Point 객체를 문자열로 리턴하는 toString()메소드를 작성하라.

package chap06;
//Point 클래스에 Point 객체를 문자열로 리턴하는 tostring()메소드를 작성하라

class Point{
	private int x,y;
	public Point(int x,int y) {
		this.x=x; this.y=y;
	}
	public String toString() {
		return "Point("+x+","+y+")";
	}
}


public class ToStringEx {

	public static void main(String[] args) {
		Point a=new Point(2,3);
		System.out.println(a.toString());
		System.out.println(a);
	}

}
Point(2,3)
Point(2,3)

 

예제 6-3 : Point 클래스의 equals() 작성
문제:Point 클래스에 x,y 점 좌표가 같으면 true를 리턴하는 equals()를 작성하라.

package chap06;

class Point{
	int x,y;
	public Point(int x,int y) {
		this.x=x; this.y=y;
	}
	public boolean equals(Object obj) {
		Point p=(Point)obj; //obj를 Point 타입으로 다운 캐스팅
		if(x==p.x && y==p.y)return true;
		else return false;
	}
}
//
public class EqualsEx {

	public static void main(String[] args) {
		Point a=new Point(2,3);
		Point b=new Point(2,3);
		Point c=new Point(3,4);
		if(a==b)System.out.println("a==b");
		if(a.equals(b))System.out.println("a is equal to b");
		if(a.equals(c))System.out.println("a is equal to c");
	}

}
//출력결과
a is equal to b

 

예제 6-4 : Rect 클래스와 equals() 메소드 만들기 연습
문제: int타입의 width( 너비 ), 높이 ) 필드를 가지는 Rect 클래스를 작성하고 , 면적이 같으면 두
Rect 객체가 같은 것으로 판별하는 equals() 를 작성하라.

package chap06;

//import chap06_assign.Point;

//int 타입의 width(너비), height(높이) 필드를 가지는 Rect 클래스를 작성하고, 면적이 같으면 두 Rect 객체가 같은 것으로 판별하는 equals()를 작성하라.
class Rect{
	int width, height;
	public Rect(int width, int height) {
		this.width=width;this.height=height;
	}
	public boolean equals(Rect p) {
	Point p =(Point)obj ; // obj 를 Point 타입으로 다운 캐스팅
	if(width*height == p.width*p.height ) return true;
	else return false;
	}
}


public class RectEx {

	public static void main(String[] args) {
		Rect a=new Rect(2,3); //면적 6
		Rect b=new Rect(3,2); //면적 6
		Rect c=new Rect(3,4); //면적 12
		
		if(a.equals(b))System.out.println("a is equal to b");
		if(a.equals(c))System.out.println("a is equal to c");
		if(a.equals(b))System.out.println("b is equal to c");
		
	}

}
//출력결과
a is equal to b

 

예제 6-5 : Wrapper 클래스 활용
문제: 다음은 Wrapper 클래스를 활용하는 예이다. 다음 프로그램의 결과는 무엇인가?

package chap06;
//Wrapper 클래스를 활용하는 예

public class WrapperEx {

	public static void main(String[] args) {
		//Character 사용
		System.out.println(Character.toLowerCase('A'));
		char c1='4', c2='F';
		if(Character.isDigit(c1)) {//문자 c1이 숫자이면 true
			System.out.println(c1+"는 숫자");
		}
		if(Character.isAlphabetic(c2)) {
			System.out.println(c2+"는 영문");
		}
		
		//Integer 사용
		System.out.println(Integer.parseInt("28"));
		System.out.println(Integer.toString(28));
		System.out.println(Integer.toBinaryString(28));
		System.out.println(Integer.bitCount(28));
		Integer i=Integer.valueOf(28);
		System.out.println(i.doubleValue()); //정수를 double 값으로 변환. 28.0
		
		//Double 사용
		Double d=Double.valueOf(3.14);
		System.out.println(d.toString()); //Double을 문자열 "3.14"로 전환
		System.out.println(Double.parseDouble("3.14")); // 문자열을 실수 3.14로 전환
		
		//Boolean 사용
		boolean b=(4>3); //b는 true
		System.out.println(Boolean.toString(b));
		System.out.println(Boolean.parseBoolean("false"));
	}

}
//출력결과
a
4
는 숫자
F
는 영문
자
28
28
11100
3
28.0
3.14
3.14
true
false
41

 

예제 6-6 : String을 활용하여 문자열 다루기

package chap06;

public class StringEx {
	public static void main(String[] args) {
		String a=new String(" C#");
		String b=new String(",C++");
		
		System.out.println(a+"의 길이는 "+ a.length());
		System.out.println(a.contains("#"));
		
		a=a.concat(b); //문자열 연결
		System.out.println(a);
		
		a=a.trim(); //문자열 앞 뒤의 공백 제거
		System.out.println(a);
		
		a=a.replace("C#","Java"); //문자열 대치
		System.out.println(a);
		
		String s[]=a.split(","); //문자열 분리
		for(int i=0;i<s.length;i++) {
			System.out.println("분리된 문자열"+i+":"+s[i]);
		}
		
		a=a.substring(5); //인덱스 5부터 끝까지 서브 스트링 리턴
		System.out.println(a);
		
		char c=a.charAt(2);
		System.out.println(c);
	}

}
//출력결과
C#의 길이는 3
true
C#,C++
C#,C++
Java,C++
분리된 문자열 0: Java
분리된 문자열 1: C++
C++
+

 

예제 6-7 : StringTokenizer를 이용한 문자열분리
문제:"name=kitae&addr=seoul&age =21" 를 '&'문자를 기준으로 분리하는 코드를 작성하라.

package chap06;
import java.util.StringTokenizer;

public class StringTokenizerEx {

	public static void main(String[] args) {
		String query="name=kitae&addr=seoul&age=21";
		StringTokenizer st=new StringTokenizer(query,"&");
	
		int n=st.countTokens();
		System.out.println("토큰 개수="+n);
		
		while(st.hasMoreTokens()) {
			String token=st.nextToken();	//토큰 얻기
			System.out.println(token);	//토큰 출력
		}
	}

}
//출력결과
토큰 개수 = 3
name=kitae
addr=seoul
age=21

 

예제 6-8 : Math 클래스 활용

package chap06;

public class MathEx {

	public static void main(String[] args) {
		System.out.println(Math.abs(-3.14));//절댓값
		System.out.println(Math.sqrt(9.0));//제곱근
		System.out.println(Math.exp(2));//e의 제곱
		System.out.println(Math.round(3.14));//반올림
		
		//[1,45] 사이의 정수형 난수 5개 발생
		System.out.print("이번주 행운의 번호는  ");
		for(int i=0; i<5; i++) {
			System.out.print((int)(Math.random()*45+1)+" ");//난수 발생
		}
	}

}
//출력결과
3.14
3.0
7.38905609893065
3
이번주 행운의 번호는 14 44 21 36 17