Math 클래스

서지은·2024년 7월 7일

JAVA 개념정리

목록 보기
6/13
post-thumbnail

java.lang.Math클래스에서 제공하는 random()메소드 호툴하면 매번 다른 랜덤값을 받을 수 있다.

Math.random()호출시 -> 0.0 ~ 0.9999999999사이의 랜덤값을 반환
0 <= 1.0

int num = Math.random() //double형이라서 int로 랜덤값을 받을수 없다.

int num = (int)(Math.random() * 10) -> 0 ~ 9

int num = (int)(Math.random() * 10) + 1 -> 1 ~ 10

int num = (int)(Math.random() * ((최대값+1) - 최소값)) = 최소값

예시

// random(5~50)한 순자 n을 생성해서 1부터 n까지의 숫자중 짝수만 출력해라(50포함)
// random 수 : 10
// 2 4 6 8
		
// int num = (int)(Math.random() * ((최대값 + 1) - 최소값)) + 최소값 
		
		int n;
		n = (int)(Math.random() * 46) + 5;
		
		System.out.println("random 수 : " + n);
		for(int i = 1; i <= n; i++) {
			if(i % 2 == 0) {
				System.out.print(i + " ");
			}
		}

charAt()

-char형은 Scanner을 통해 바로 입력받는 방법이 없다.
따라서 next()를 통해 String을 Scanner로 받은 다음, charAt(0)로 char형으로 바꿔주는 방법을 사용해야한다.

-지정한 숫자(index)의 단일 문자 값을 반환한다.

표현법1

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String s = sc.next();
		char c = s.charAt(0);
		
		System.out.println(c);
	}
}

표현법2

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		char c = sc.next().charAt(0);
		
		System.out.println(c);
	}
}
  • 문자열(string) : 문자열을 설정한다.

  • 숫자(index) : 0 ~ 문자열 길이보다 작은 정수를 설정한다.

    예시

		//사용자에게 문자열을 입력받아 해당 문자열의 짝수자리 글자만 출력
		//문자열 입력 : hello
		//el
		
		String str;
		Scanner sc = new Scanner(System.in);
		system.out.print("문자열 입력 : ");
		str = sc.next();

		for(int i = 0; i < str.length(); i++) {
          if(i % 2 == 1) {
            System.out.print(i);
            
            char ch = sc.next().charAt();

문자열.length() : 문자열의 길이를 구하는 방법

0개의 댓글