Java 유용한 클래스

김정훈·2024년 4월 24일

Java

목록 보기
25/48

유용한 클래스

1. java.lang.Math 클래스

  • 수학 관련 편의 기능 클래스

  • 정적 메서드로 구성

    • abs() : 절대값

    • ceil() : 올림

    • floor() : 버림

    • round() : 반올림

    • pow() : 제곱

    • random() : 0~1 미만의 난수

    • sqrt() : root값

package exam04;

import static java.lang.Math.*;

public class Ex01 {
    public static void main(String[] args) {
        System.out.println(abs(-10));
        System.out.println(ceil(10.2));
        System.out.println(floor(10.2));
        System.out.println(Math.round(10.5));
        System.out.println(Math.pow(5,2));
        System.out.println(Math.random());
        System.out.println(sqrt(25));
    }
}

2. java.util.Objects 클래스

  • 객체를 다룰떄 사용하는 편의 기능 모음
  • 모든 메서드가 정적
    • equals : 두객체간의 주소 비교
    • deepequals : 중첩된 객체를 재귀적으로 주소비교
    • int hash(Object.. values) :
    • int hashCode(Object o) :
    • boolean isNull(..) : 참조변수가 null 인지 체크
    • boolean nonNull(..) : 참조변수가 null 아닌지 체크
    • requirNonNullElse(..) : 특정 변수가 null이면 기본값을 부여

3. java.util.Random 클래스

import java.util.Random;

public class Ex01 {
    public static void main(String[] args) {
        Random rand = new Random();
        for (int i = 0 ; i < 6; i++){
            int num = rand.nextInt();
            System.out.println(num);
            
            boolean bool = rand.nextBoolean();
            System.out.println(bool);
        }
    }
}

4. java.util.Scanner 클래스

데이터를 입력 받을 때 사용하는 편의 클래스

  • InputStream System.in : 터미널에서 입력
  • File, FileInputStram : 파일
import java.util.Scanner;

public class Ex02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);//터미널입력
        System.out.println("이름을 입력하세요 : ");
        String name = sc.nextLine();
        System.out.println(name);
    }
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Ex03 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("data.txt"));

        int total = 0 ;
        while(sc.hasNextLine()){
            int num = sc.nextInt();
            System.out.println(num);
            total += num;
        }
        System.out.println(total);

    }
}

5. java.util.StringTokenizer 클래스

  • 구문 문자를 가지고 문자를 분리
  • 토큰 : 구문문자
import java.util.StringTokenizer;

public class Ex04 {
    public static void main(String[] args) {
        String fruits = "Apple#Orange,Melon#Banana";
        StringTokenizer st = new StringTokenizer(fruits,"#,_+");
        while(st.hasMoreElements()){
            String fruit = st.nextToken();
            System.out.println(fruit);
        }
    }
}
profile
안녕하세요!

0개의 댓글