JAVA :: 그 외의 다양한 클래스

smi·2021년 2월 1일
2

JAVA (자바)

목록 보기
11/62
post-thumbnail

📝 StringBuffer 클래스

스트링을 다루는 클래스로서, 내부에 가변 크기의 버퍼를 가지고 문자의 개수에 따라 버퍼 크기를 자동 조절한다.

⚠ 스트링의 수정이 가능하다.

💡 메소드

메소드설명
append(값)StringBuffer, StringBuilder 뒤에 값을 붙인다
insert(인덱스, 값)특정 인덱스부터 값을 삽입한다
delete(인덱스, 인덱스)특정 인덱스부터 인덱스까지 값을 삭제한다
indexOf(값)값이 어느 인덱스에 들어있는지 확인한다
substring(인덱스, 인덱스)인덱스부터 인덱스까지 값을 잘라온다
length()길이를 확인한다.
replace(인덱스, 인덱스, 값)인덱스부터 인덱스까지 값으로 변경한다
reverse()글자 순서를 뒤집는다

  • 예시
StringBuffer sb = new StringBuffer("This"); // 객체생성
sb.append("is pencil.");   // sb = "This is pencil."
sb.insert(7, " my");       // sb = "This is my pencil."
sb.replace(8, 10, "your"); // sb = "This is your pencil."
System.out.println(sb); 
  • 결과

This is your pencil.


📝 StringTokenizer 클래스

문자열을 분리하기 위해 사용한다.

💡 구분 문자

문자열을 분리할 때 사용되는 기준 문자

💡 토큰

구분 문자로 분리된 문자열

💡 주요 메소드

  • 예시
import java.util.StringTokenizer;
public class postingex {
    public static void main(String[] args) {
        String company = "Samsung&Apple&Google";
        StringTokenizer st = new StringTokenizer(company, "&");

        int n = st.countTokens(); //분리된 토근의 개수
        System.out.println("분리된 토큰의 개수 = "+n);
        while(st.hasMoreTokens()) // 다음 토근이 있으면 1 없으면 0
        {
            String token = st.nextToken(); // 분리된 토근 얻기
            System.out.println(token);
        }
    }
}
  • 결과
분리된 토큰의 개수 = 3
Samsung
Apple
Google

📝 Math 클래스

'Math.메소드'

기본적인 산술 연산을 수행하는 메소드를 제공하는 클래스이다.

💡 주요 메소드

+ pow(a, b) : a의 b제곱

⚠ 모든 메소드가 static 타입이다.

  • random() 예시
for(int i = 0; i < 10; i++)
{
    int n = (int)(Math.random()*100 + 1); // 1~100까지의 랜덤 정수
}

Reference

명품 자바 에센셜 (2014, 황기태) / 혼자 공부하는 자바 (2019, 신용권)

profile
공부한 거 올려요 :)

0개의 댓글