자기개발/Java

Chapter 9 java.lang 패키지

실버블렛 2012. 1. 21. 15:53
반응형


----------------------------------------------------------------------------------------
class CardToString
{
 public static void main(String[] args)
 {
  Card c1 = new Card();
  Card c2 = new Card();
    
  System.out.println(c1.toString());
  System.out.println(c2.toString());
 }
}

class Card {
 int number;
 String kind;

 Card(){
  this("SPACE", 1);
 }

 Card(String kind, int number){
  this.kind = kind;
  this.number = number;
 }
}
----------------------------------------------------------------------------------------
class CardToString2
{
 public static void main(String[] args)
 {
  Card c = new Card("HEART", 10);
     
  System.out.println(c.toString());  
 }
}

class Card {
 int number;
 String kind;

 Card(){
  this("SPACE", 1);
 }

 Card(String kind, int number){
  this.kind = kind;
  this.number = number;
 }

 public String toString(){
  return "kind : " + kind + ", number : " + number;
 }
}
----------------------------------------------------------------------------------------
class CardToString2
{
 public static void main(String[] args)
 {
  Card c1 = new Card();
  Card c2 = new Card();
    
  System.out.println(c1.toString());
  System.out.println(c2.toString());
 }
}

class Card {
 int number;
 String kind;

 Card(){
  this("SPACE", 1);
 }

 Card(String kind, int number){
  this.kind = kind;
  this.number = number;
 }
}
----------------------------------------------------------------------------------------
class  CloneEx1
{
 public static void main(String[] args)
 {
  Point original = new Point(3, 5);
  Point copy = (Point)original.clone();

  System.out.println(original.toString());
  System.out.println(copy.toString());
  // System.out.println(copy);
 }
}

class Point implements Cloneable{
 int x;
 int y;
 Point(int x, int y){
  this.x = x;
  this.y = y;
 }

 public String toString(){
  return "x = " + x + ", y = " + y;
 }

 public Object clone(){
  Object obj = null;
  try{
   obj = super.clone();   
  }catch (CloneNotSupportedException e){ }
  return obj;
 }
}

----------------------------------------------------------------------------------------
import java.util.*;

class CloneEx2 
{
 public static void main(String[] args)
 {
//  int[] arr = new int[]{1,2,3,4,5};
  int[] arr = {1,2,3,4,5};
  int[] arrClone = arr.clone();
//        int[] arrClone = new int[arr.length];
//   System.arraycopy(arr, 0, arrClone, 0, arr.length);

  arrClone[0] = 6;

  System.out.println(Arrays.toString(arr));
  System.out.println(Arrays.toString(arrClone));
 }
}
----------------------------------------------------------------------------------------
class EqualsEx1
{
 public static void main(String[] args)
 {
  Value v1 = new Value(10);
  Value v2 = new Value(10);

  if (v1.equals(v2)){
   System.out.println("v1과 v2는 같습니다.");
  } else {
   System.out.println("v1과 v2는 다릅니다.");
  }

  v2 = v1;

  if (v1.equals(v2)){
   System.out.println("v1과 v2는 같습니다.");
  } else {
   System.out.println("v1과 v2는 다릅니다.");
  }  
 }
}

class Value {
 int value;

 Value(int value){
  this.value = value;
 }
}

----------------------------------------------------------------------------------------
class EqualsEx2
{
 public static void main(String[] args)
 {
  Person p1 = new Person(8011081111222L);
  Person p2 = new Person(8011081111222L);

  if (p1==p2){
   System.out.println("p1과 p2는 같은 사람입니다.");
  } else {
   System.out.println("p1과 p2는 다른 사람입니다.");
  }

  if (p1.equals(p2)){
   System.out.println("p1과 p2는 같은 사람입니다.");
  } else {
   System.out.println("p1과 p2는 다른 사람입니다.");
  }
 }
}

class Person{
 long id;

 public boolean equals(Object obj){
  if (obj != null && obj instanceof Person ){
   return id == ((Person)obj).id;
  } else { return false; }
 }

 Person(long id){
  this.id = id;
 }
}
----------------------------------------------------------------------------------------
class HashCodeEx1 
{
 public static void main(String[] args)
 {
  String str1 = new String("abc");
  String str2 = new String("abc");

  System.out.println(str1.hashCode());
  System.out.println(str2.hashCode());
  System.out.println(System.identityHashCode(str1));
  System.out.println(System.identityHashCode(str2));
 }
}

----------------------------------------------------------------------------------------
class  StringBufferEx1
{
 public static void main(String[] args)
 {
  StringBuffer sb = new StringBuffer();
  StringBuffer sb2 = new StringBuffer();

  if (sb == sb2){
   System.out.println("sb == sb2 ? true");
  } else {
   System.out.println("sb == sb2 ? false");
  }

  if (sb.equals(sb2)){
   System.out.println("sb.equals(sb2) ? true");
  } else {
   System.out.println("sb.equals(sb2) ? false");
  }


  //StringBuffer의 내용을 String으로 변환한다.
  String s = sb.toString();
  String s2 = sb2.toString();

  if (s.equals(s2)){
   System.out.println("s.equals(s2) ? true");
  } else {
   System.out.println("s.equals(s2) ? false");
  }
 }
}

----------------------------------------------------------------------------------------
public class StringCount
{
 // count = 문자열 갯수, source = 문자열   기본값으로 명시적 초기화
 private int count;
 private String source = "";

 // 생성자를 통해 입력한 문자열 초기화
 public StringCount(String source){
  this.source = source;
 }

 //메서드를 통해 문자열 수 계산
 public int stringCount(String s){
  return stringCount(s, 0);
 }

 public int stringCount(String s, int pos){  //pos = 현재 index
  int index = 0;
  if (s == null || s.length() ==0){
   return 0;
  }
  if ((index = source.indexOf(s, pos)) != -1){
   count ++;
   stringCount(s, index + s.length());  //index(찾은 문자열위치) + 찾는 문자수 = 다음에 찾기 사작할 위치(pos)
  }
  return count;
 }

 public static void main(String[] args)
 {
  String str = "aabbccAABBCCaa"; //문자열 저장
  System.out.println(str); // 저장한 문자열 출력
  StringCount sc = new StringCount(str);  //문자열에서 찾는문자열의 수를 계산할 객체 생성
  System.out.println("aa를 " + sc.stringCount("aa") + "개 찾았습니다."); //문자열에서 찾는 문자열의 수 계산하여 출력  
 } 
}
----------------------------------------------------------------------------------------
class StringEx1
{
 public static void main(String[] args)
 {
  String str1 = "abc";
  String str2 = "abc";
  System.out.println("String str1 = \"abc\";");
  System.out.println("String str2 = \"abc\";");

  if (str1==str2){
   System.out.println("str1==str2 ? true");
  } else {
   System.out.println("str1==str2 ? false");
  }

  if (str1.equals(str2)){
   System.out.println("str1.equals(str2) ? true");
  } else {
   System.out.println("str1.equals(str2) ? false");
  }

  System.out.println();


  String str3 = new String("abc");
  String str4 = new String("abc");
  System.out.println("String str3 = new String(\"abc\");");
  System.out.println("String str4 = new String(\"abc\");");

  if (str3==str4){
   System.out.println("str3==str4 ? true");
  } else {
   System.out.println("str3==str4 ? false");
  }

  if (str3.equals(str4)){
   System.out.println("str3.equals(str4) ? true");
  } else {
   System.out.println("str3.equals(str4) ? false");
  }  
 }
}

----------------------------------------------------------------------------------------
class StringEx2
{
 public static void main(String[] args)
 {
  String s1 = "AAA";
  String s2 = "AAA";
  String s3 = "AAA";
  String s4 = "BBB";
 }
}

----------------------------------------------------------------------------------------
class StringEx3
{
 public static void main(String[] args)
 {
  String s1 = "AAA";
  String s2 = new String("AAA");

  if (s1==s2){
   System.out.println("s1==s2 ? true");
  }else {
   System.out.println("s1==s2 ? false");
  }

  s2 = s2.intern();
  System.out.println("s2에 intern을 호출한 후");

  if (s1==s2){
   System.out.println("s1==s2 ? true");
  }else {
   System.out.println("s1==s2 ? false");
  }
 }
}

----------------------------------------------------------------------------------------
class StringEx4
{
 public static void main(String[] args)
 {
  String[] words = {new String("aaa"), new String("bbb"), new String("ccc")};

  for (int i=0; i<words.length; i++){
   if (words[i]=="ccc"){
    System.out.println("words에서 ==연산자로 찾았습니다.");
   }
   if (words[i].equals("ccc")){
    System.out.println("words에서 equals메서드로 찾았습니다.");
   }
  }

  for (int i=0; i<words.length; i++){
   words[i] = words[i].intern();
  }  
  System.out.println("<< String배열 words의 문자열에 intern메서드를 수행한 후 >>");

  for (int i=0; i<words.length; i++){
   if (words[i]=="ccc"){
    System.out.println("words에서 ==연산자로 찾았습니다.");
   }
   if (words[i].equals("ccc")){
    System.out.println("words에서 equals메서드로 찾았습니다.");
   }
  }
 }
}

----------------------------------------------------------------------------------------
class StringEx5
{
 static String s;
 static String s2 = "";

 public static void main(String[] args)
 {
  for (int i=1; i<10; i++){
   s += i;  // s = s + i;
   s2 += i;
  }

  System.out.println(s);
  System.out.println(s2);
 }
}

----------------------------------------------------------------------------------------
class StringEx6
{
 public static void main(String[] args)
 {
  //크기가 0인 배열 char배열을 생성한다.
  char[] cArr = new char[0];
  String s = new String(cArr);

  System.out.println("cArr.length = " + cArr.length);
  System.out.println("@@@" + s + "@@@");
 }
}

----------------------------------------------------------------------------------------
class StringEx7
{
 public static void main(String[] args)
 {
  int value = 100;
  String strvalue = String.valueOf(value);

  System.out.println(strvalue);

  int value2 = 100;
  String strvalue2 = "" + 100;

  System.out.println(strvalue2);
 }
}

----------------------------------------------------------------------------------------
class StringEx8
{
 public static void main(String[] args)
 {
  String[] number = {"1", "2", "3", "4", "5"};
  String result1 = "";
  int result2 = 0;

  for (int i=0; i<number.length; i++){
   result1 += number[i];
   result2 += Integer.parseInt(number[i]);
  }

  System.out.println(result1);
  System.out.println(result2);
 }
}

----------------------------------------------------------------------------------------
class StringEx9
{
 public static void main(String[] args)
 {
  String fullName = "Hello.java"; 

  int index = fullName.indexOf('.');

  String fileName = fullName.substring(0, index);

  String ext = fullName.substring(index + 1, fullName.length());
//  String ext = fullName.substring(index + 1);

        System.out.println(fullName + "의 확장자를 제외한 이름 " + fileName);
  System.out.println(fullName + "의 확장자는 " + ext);  
 }
}

----------------------------------------------------------------------------------------
class StringReplace
{
 

  private String source = "";
  private StringBuffer buffer;
  private int length;

  public int length(){
   return length;
  }

  StringReplace(String source){
   this.source = source;
   buffer = new StringBuffer(length + 100);
  }
  public String replace(String old, String nw){
   return replace(old, nw, 0);
  }

  public String replace(String old, String nw, int pos){
   int index = 0;
   if (old == null || nw == null){
    return "null";
   }

   if ( (index = source.indexOf(old, pos)) != -1){
    buffer.append(source.substring(pos, index));
    buffer.append(nw);
    replace(old, nw, index + old.length() );
   } else {
    buffer.append(source.substring(pos) );
   }

   return buffer.toString();
  }

 public static void main(String[] args)
 {
  String str = "000111222333111222333";
  System.out.println(str);
  StringReplace sr = new StringReplace(str);
  System.out.println(sr.replace("111","AAA"));
 } 
}

/*
문자열의 일부를 다른 문자열로 치환하는 클래스를 만들기 위해
1.입력받을 문자열(source)와 치환한 문자열(StringBuffer)을 멤버변수로 선언하는 클래스 StringReplace를 만든다.
2.작업할 문자를 입력받는 생성자 StringReplace(String source)를 작성한다.
3.작업을 시작할 위치와 문자열 A와 B를 입력 받아 A를 B로 치환하는 replace(String old, String nw, int pos)를 만든다.
   1.입력한 값이 유효한지 판단한다.
   2.source에서 해당 문자열을 발견할시 치환한다.
   3.발견한 위치 이후부터 다시 치환을 시작한다.(재귀호출 사용)
   4.더 이상 치환할 문자열을 발견 못하면 나머지 문자열을 작업 결과에 붙인다.
   5.문자열의 처음부터 치환을 하는 replace(String old, String nw)를 작성한다.
   6.StringReplace의 기능을 테스트할 코드를 작성한다.
*/
----------------------------------------------------------------------------------------

class TicketDTO {
    String train = "";
    int smallPrice = 0;
    int smallCount = 0;
    int bigPrice = smallPrice * 2;
    int bigCount = 0;
    String start = "";
    String arrival = "";
    int tot = 0;
}


class TicketProcess {
    public void input(TicketDTO dto){
        dto.train = "KTX";
        dto.smallPrice = 10000;
        dto.smallCount = 0;
        dto.bigPrice = dto.smallPrice * 2;
        dto.bigCount = 2;
        dto.start = "서울용산역";
        dto.arrival = "광주역";
    }
    public void total(TicketDTO dto){
        dto.tot = (dto.smallPrice * dto.smallCount) + (dto.bigPrice + dto.bigCount);
    }
    public void discount(TicketDTO dto){
        if (dto.smallCount + dto.bigCount >= 5){
            dto.tot = (dto.tot - (int)(dto.tot * 0.05));            
        }       
    }
    public void print(TicketDTO dto){
        System.out.println("열차종류  : " + dto.train);
        System.out.println("금액(소) : " + dto.smallPrice);
        System.out.println("매수(소) : " + dto.smallCount);
        System.out.println("금액(대) : " + dto.bigPrice);
        System.out.println("매수(대) : " + dto.bigCount);
        System.out.println("출발지      : " + dto.start);
        System.out.println("도착지      : " + dto.arrival);
        System.out.println("할인 금액  : " + dto.tot);
    }
}


public class TicketTest {
    public static void main(String[] args) {
        TicketDTO dto = new TicketDTO();
        TicketProcess mgr = new TicketProcess();
        mgr.input(dto); // 입력: 단순한 값 할당
        mgr.total(dto); // 총 금액 계산
        mgr.discount(dto); // 할인: 승차권 5매이상 구매시 5%할인.
        mgr.print(dto); // 출력: 기본 변수 출력, 특별한 출력 형식은 없음.

    }
}


----------------------------------------------------------------------------------------
class ToStringTest
{
 public static void main(String[] args)
 {
  String str = new String("Korea");
  java.util.Date today = new java.util.Date();

  System.out.println(str);
  System.out.println(str.toString());
  System.out.println(today);
  System.out.println(today.toString());
 }
}

----------------------------------------------------------------------------------------

반응형

'자기개발 > Java' 카테고리의 다른 글

java 강좌  (1) 2012.01.30
자바 강의  (0) 2012.01.22
Chapter 8 예외처리(Exception Handling)  (0) 2012.01.21
Chapter 7 객체지향 프로그래밍 2  (0) 2012.01.21
Chapter 6 객체지향 프로그래밍 1  (0) 2012.01.21