1 / 53

제 2 주 객체의 사용

제 2 주 객체의 사용. 제 2 주 목표 다른 사람이 작성해 놓은 클래스를 이용하는 연습 API 문서를 찾아 보고 이용하는 법을 알게 됨. 라이브러리와 API Document. API: Application Programming Interface 라이브러리에 들어 있는 클래스들과 그 들이 지원하는 메소드들을 상세히 보여줌 아래 사이트에서 온라인으로 볼 수 있으며 http://java.sun.com/javase/7/docs/api/ 컴퓨터에 저장된 것을 볼 수 도 있음 (doc 폴더 ).

feoras
Download Presentation

제 2 주 객체의 사용

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 제 2주 객체의 사용 • 제 2주 목표 • 다른 사람이 작성해 놓은 클래스를 이용하는 연습 • API 문서를 찾아 보고 이용하는 법을 알게 됨 강원대학교

  2. 라이브러리와 API Document • API: Application Programming Interface • 라이브러리에 들어 있는 클래스들과 그 들이 지원하는 메소드들을 상세히 보여줌 • 아래 사이트에서 온라인으로 볼 수 있으며 http://java.sun.com/javase/7/docs/api/ 컴퓨터에 저장된 것을 볼 수 도 있음 (doc 폴더) 강원대학교

  3. The API Document 강원대학교

  4. 라이브러리에 들어 있는 클래스 이용하기 • 클래스들은 그룹으로 분류되어 있으며 이 그룹을 패키지라고 함 • Rectangle 클래스는 java.awt패키지에 들어 있음 • Rectangle 클래스의 full name = java.awt.Rectangle • 라이브러리에 있는 클래스를 프로그램에서 사용하려면 그 클래스를 import해야 함 • 프로그램 내에서 클래스의 full name을 사용할 경우 클래스를 import하지 않아도 됨 01:import java.awt.Rectangle; java.awt.Rectangle 강원대학교

  5. 패키지 가져오기(Importing Packages) • java.lang 패키지에는 가장 기본적이며 많이 사용되는 클래스들이 들어 있음 • java.lang 패키지에 들어 있는 클래스들은 import 하지 않고 사용할 수 있음 • String 클래스와 System 클래스는 java.lang 패키지에 들어 있음 강원대학교

  6. Rectangle Objects 라이브러리 클래스 활용 예 class Rectangle • 클래스는 그에 속하는 각 객체의 상태를 나타내는 데이터와 수행 가능한 메소드들을 정의한다. • 이 중 데이터 부분을 필드(field) 혹은 상태변수라고 부른다. 강원대학교

  7. Rectangle Objects 라이브러리 클래스 활용 예 (0, 0) 30 x (x, y) 사각형의 위치 (30, 20) Rectangle의 field 20 int height int width int x int y height y width 강원대학교

  8. 강원대학교

  9. 강원대학교

  10. 객체를 만드는(construct) 법(Constructing Objects) • new는 연산자(operator)로서 Rectangle 클래스의 객체를 하나 구성하여 반환한다. • 새로이 구성되는 Rectangle 객체는 주어진 인자에 맞춰 만들어진다. 위치가 (5, 10)이고 폭이 20, 높이가 30 • 새로이 만들어진 객체는 Rectangle 타입 변수인 box에 저장된다. Rectangle box = new Rectangle(5, 10, 20, 30); new Rectangle() // constructs a rectangle with its top-left corner // at the origin (0, 0), width 0, and height 0 강원대학교

  11. 객체를 만드는(construct) 법(Constructing Objects) • 구성자 (생성자, constructor) Rectangle box = new Rectangle(5, 10, 20, 30); 모든 클래스는 한 개 이상의 구성자를 갖는다. new Rectangle() // constructs a rectangle with its top-left corner // at the origin (0, 0), width 0, and height 0 강원대학교

  12. File MoveTester.java 01:import java.awt.Rectangle; 02: 03:public classMoveTester 04:{ 05:public static voidmain(String[] args) 06:{ 07:Rectangle box =newRectangle(5, 10, 20, 30); 08: 09:// Move the rectangle 10:box.translate(15, 25); 11: 12:// Print information about the moved rectangle 13:System.out.println("After moving, the top-left corner is:"); 14:System.out.println(box.getX()); 15:System.out.println(box.getY()); 16:} 17:} 강원대학교

  13. File MoveTester.java 07:Rectangle box =newRectangle(5, 10, 20, 30); 08: 09:// Move the rectangle 10:box.translate(15, 25); 11: 12:// Print information about the moved rectangle 13:System.out.println("After moving, the top-left corner is:"); 14:System.out.println(box.getX()); 15:System.out.println(box.getY()); After moving, the top-left corner is: 20.0 35.0 강원대학교

  14. java.util.Scanner • Scanner in = new Scanner(System.in); • String st = in.next(); • String line = in.nextLine(); • inti= in.nextInt(); 강원대학교

  15. java.util.Scanner • next() • nextLine() • nextInt() • nextShort() • nextLong() • nextDouble() • nextFloat() • nextBoolean() 강원대학교

  16. nextLine() 메소드 • Scanner를 input의 다음 행의 시작 위치로 이동시키고, 이 과정에서 지나친 모든 문자들로 구성된 String 객체에 대한 참조를 반환한다. (행 분리 기호 제외, 공백 포함)

  17. nextLine() 메소드 System.out.print("Enter String on one line: "); String message = input.nextLine(); System.out.print("Enter an integer in the range 0-25: "); intnum = input.nextInt() ; Hello 8 message는 “Hello”를 가리킴 num은 8 .

  18. nextLine() 메소드 System.out.print("Enter an integer in the range 0-25: "); intnum = input.nextInt() ; System.out.print("Enter String on one line: "); String message = input.nextLine(); 8 Hello num은 8 message는null을 가리킴 .

  19. nextLine() 메소드 • 문자열을 한 행씩 읽기 위해 nextLine()을 사용하는 것은 문제를 발생시키지 않는다. • 하지만, next(), nextInt(), nextDouble()과 같은 다른 Scanner 호출과 nextLine()을 혼합하여 사용할 때는 주의해야 한다.

  20. java.lang.String • 자바 String 객체는 변경할 수 없다. 읽기 전용(read-only)이다.  • String s = "E.T."; s = s.toLowerCase(); * “E.T.”에는 더 이상 접근할 수 없다.

  21. String 메소드 • char charAt(int index) • 인덱스 i에 있는 문자를 반환한다. • 문자열의 인덱스는 0부터 시작된다. • 예제String s = “Titanic”;s.charAt(3) returns ‘a’

  22. String 메소드 • intcompareTo(String t) • 문자의 ASCII 값을 사용하여 두 개의 문자열을 한 문자씩 비교한다. s < t이면 s.compareTo(t)는 음수를 반환한다. s == t이면s.compareTo(s)는 0을 반환한다. s > t이면 s.compareTo(t)는 양수를 반환한다. • String s = “Shrek”;String t = “Star Wars”;s.compareTo(t)는 음수를 반환한다.s.compareTo(s)는 0을 반환한다.t.compareTo(s)는 양수를 반환한다.

  23. String 메소드 • intcompareTolgnoreCase(String t) • compareTo(...)와 비슷하지만 대소문자를 구분하지 않는다. • String s = “E.T.”;String t = “e.t.”; s.compareToIgnorecase(t) returns 0.

  24. String 메소드 • booleanendsWith(String suffix) • s.endsWith(t)는 t가 s의 접미사(suffix)이면 참(true)을 반환 • String s = “Forrest Gump”;s.endsWith(“ump”) returns true

  25. String 메소드 • booleanstartsWith(String prefix) • s.startsWith(t)는 t가 s의 접두사(prefix)이면 참을 반환한다. • String s = “ ”;s.startsWith(“Jur”) returns true s.startsWith(“jur”) returns false

  26. String 메소드 • boolean equals(Object t)(여기서의 매개변수 타입 Object는 나중에 이해하게 됨. 지금은 매개변수를 String으로 간주) • s.equals(t)는 s와 t가 동일하면 참을 반환한다. • String s = “FINDING NEMO”;String t = “Finding Nemo”;s.equals(t) returns falses.equals("FINDING NEMO") returns true

  27. String 메소드 • booleanequalslgnoreCase(String t) • s.equalsIgnoreCase(t)는 대소문자를 따지지 않고 s와 t가 동일하면 참을 반환한다. • String s = “FINDING NEMO”;String t = “Finding Nemo”;s.equalsIgnorecase(t) returns true

  28. String 메소드 • intindexOf(String t) • s.indexOf(t)는 t가 처음 나타나는 s에서의 인덱스를 반환하고, t가 s의 부분 문자열(substring)이 아니면 -1을 반환한다. • String s = "The Lord Of The Rings";s.indexOf("The") returns 0;s.indexOf("Bilbo") returns –1.

  29. String 메소드 • intindexOf(String t, int from) • s.indexOf(t, from)은 인덱스 from에서 시작하여 t가 처음 나타나는 s에서의 인덱스를 반환한다. 검색에 실패하면 -1을 반환한다. • String s = "The Lord Of The Rings";s.indexOf("The", 6) returns 12;.

  30. String 메소드 • intlength( ) • s.length()는 s에 있는 문자들의 수를 반환한다. • String s = “Jaws”;s.length() returns 4

  31. String 메소드 • String replace( char oldChar, char newChar) • s.replace(oldCh, newCh)는 oldCh가 나타나는 모든 부분을 newCh로 대체하여 얻어진 문자열을 반환한다. • String s = “Harry Potter”;s.replace (‘r’,’m’) returns “Hammy Pottem”

  32. String 메소드 • String substring(int index) • s.substring(index)는 index보다 크거나 같은 인덱스의 모든 문자들로 구성된 s의 부분 문자열을 반환한다. • String s = “The Sixth Sense”;s.substring(7) returns “th Sense”

  33. String 메소드 • String substring(int start, int end) • s.substring(start, end)는 start보다 크거나 같고 end 미만의 인덱스를 갖는 모든 문자들로 구성된 s의 부분 문자열을 반환한다. • String s = “The Sixth Sense”;s.substring(7, 12) returns “th Se”

  34. String 메소드 • String toLowerCase() • s.toLowerCase()는 s로부터 모든 대문자를 소문자로 대체하여 형성된 문자열을 반환한다. • String s = “The Lion King”;s.toLowerCase() returns “the lion king”

  35. String 메소드 • String toUpperCase() • s.toUpperCase()는 s로부터 모든 소문자를 대문자로 대체하여 형성된 문자열을 반환한다. • String s = “The Lion King”;s. toUpperCase() returns “THE LION KING”

  36. String 메소드 • String trim() • s.trim()은 문자열의 앞과 뒤에 있는 공백을 제거한 문자열을 반환한다. • String s = “ Attack of the Killer Tomatoes “;s.trim() returns “Attack of the Killer Tomatoes”

  37. equals(...)와 == • 두 String 객체의 문자 순서가 같은지를 결정하려고 할 때는 equals(...) 메소드를 사용해야 한다. • == 연산자는 문자가 아닌 참조를 비교한다.

  38. equals(...)와 ==

  39. equals(...)와 ==

  40. 문자열 연결 • 연결(concatenation)은 문자열들을 서로 이어주는 조작 • + 연산자 또는 += 연산자 사용

  41. 문자열 연결

  42. StringBuilder 클래스 • String 객체는 변경 불가능하다. • 일단 생성되면, String 객체는 변경할 수 없다. • StringBuilder객체는 변경이 가능하다. • 새로운 StringBuilder객체를 생성하지 않고 StringBuilder객체에 문자를 추가하거나 StringBuilder객체에서 문자를 제거할 수 있다.

  43. StringBuilder 클래스 String에 추가와 StringBuilder에 추가

  44. StringBuilder 클래스 • StringBuilder객체를 생성하기 위해서는 new 연산자를 사용한다:  • StringBuilder s = new StringBuilder(); // 초기 용량은 16개 문자 • StringBuilder s = new StringBuilder(50); // 초기 용량은 50개의 문자 • StringBuilder s = new StringBuilder (“Hello”); // s를 “Hello”로 초기화 • StringBuilder객체의 용량은 필요한 만큼 자동적으로 확장된다.

  45. 문제 • 키보드로부터 읽어들인 문자열을 순서를 바꿔 출력하는 프로그램을 작성하시오. 강원대학교

  46. 문제 • Rectangle 클래스의 메소드들을 테스트하는 프로그램을 작성하시오. 강원대학교

  47. java.util.Random intnextInt(int n): 0보다 크거나 같고 n보다 작은 정수 값을 반환 double nextDouble(): 0.0보다 크거나 같고 1.0보다 작은 double 형 값을 반환 강원대학교

  48. java.util.Random Random die = new Random(); int dice = (die.nextInt(6) + 1) + (die.nextInt(6) + 1); • 항상 같은 순서의 “임의의” 수가 생성되도록 하는 방법 • Random(...)에 long 타입 “시드(seed)”를 전달 • Random rand = new Random(12345678); //123456768는 시드 강원대학교

  49. 문제 • 문자열을 무작위로 만들어 특정 문자열이 몇번만에 나타나는지 관찰하는 프로그램을 작성하시오. Random random = new Random(); int x = random.nextInt(26); char letter = (char)(x + 'A'); 강원대학교

  50. 코드 실행시간 측정법 class TimeTest1 { public static void main(String[] args) { long startTime = System.currentTimeMillis(); long total = 0; for (inti = 0; i < 10000000; i++) { total += i; } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println(elapsedTime); } } 강원대학교

More Related