API - Math, Scanner

JK·2022년 12월 27일
0

JAVA

목록 보기
22/28
post-thumbnail

🎈Math

  • Math 클래스의 상수
package com.lec.ex3_math;

public class Ex01_Math {
	public static void main(String[] args) {
		int a =2, b = 10;
		System.out.println("a의 b승 : " + Math.pow(a, b));
		System.out.println("-9.9의 절대값 : " + Math.abs(-9.9));
		System.out.println("a와 b 중 최소값 : " + Math.min(a, b));
		System.out.println("a와 b 중 최대값 : " + Math.max(a, b));
//		Mate의 final 변수, 
		System.out.println("PI = " + Math.PI);
	}
}
  • Math 수학 계산에 유용한 메서드들
  1. Math.ceil(올릴 실수) => double값 return ex)Math.ceil(9.1) =>10.0
  2. Math.round(반올림할 실수) => long값 return ex)Math.round(9.1) => 9
  3. Math.floor(버릴 실수) => double값 return ex)Math.floor(9.9) => 9.0
		System.out.println("소수점에서 반올림, 올림, 버림");  
		System.out.println("9.15를 올림 " + Math.ceil(9.15));  // 10.0
		System.out.println("9.15를 반올림 " + Math.round(9.15));	//9
		System.out.println("9.15를 올림 " + Math.floor(9.15));	//9.0
		
		System.out.println("소수점 한자리에서 반올림, 올림, 버림");
		System.out.println("9.15를 올림" + Math.ceil(9.15*10)/10);	//9.2
		System.out.println("9.15를 반올림" + Math.round(9.15*10)/10.0);	//9.2
		System.out.println("9.15를 버림" + Math.floor(9.15*10)/10);	//9.1
		
		System.out.println("일의 자리에서 반올림, 올림, 버림");
		System.out.println("85를 올림" + Math.ceil(85/10.0)*10);	//90.0
		System.out.println("85를 반올림" + Math.round(85/10.0)*10);	// 90
		System.out.println("85를 버림" + Math.floor(85/10.0)*10);	// 80.0

🎈random

Math.random()보다 난수 표현하기 용이하다.

		Random random = new Random();
		System.out.println("int 난수 : " + random.nextInt()); // 정수 난수
		System.out.println("Double 난수 : " + random.nextDouble()); // 실수 난수
		System.out.println("true/false 중 난수 : " + random.nextBoolean());
		System.out.println("0~100까지의 정수 난수 : " + random.nextInt(101));
		System.out.println("1~45까지의 정수 난수 : " + (random.nextInt(45) + 1));
		System.out.println("가위(0), 바위(1), 보자기(2) 중 하나 : " + random.nextInt(3));
  • 결과
1~45까지 정수 난수 : 16
int 난수 : -403550985
Double 난수 : 0.019118318055504457
true/false 중 난수 : false
0~100까지의 정수 난수 : 92
1~45까지의 정수 난수 : 31
가위(0), 바위(1), 보자기(2) 중 하나 : 1

- 로또 번호 출력해보기

  • 6자리 난수 발생시키기
  • 중복값 없게 하기
  • 오름차순으로 정렬
public class Ex04_lotto {
	public static void main(String[] args) {
		int[] lotto = new int[6];      //lotto 6자리 방 만들기
		int i, j;
		int temp;    //난수 변수
		Random random = new Random();
		for(i=0 ; i<lotto.length ; i++) {
			do { //발생된 난수가 중복되었는지 체크
				temp = random.nextInt(45)+1;	// temp = (int)(Math.random()*45+1); 
				for(j=0 ; j<i ; j++) {    
					if(lotto[j] == temp) {
						break;
					} // if - temp랑 같은 번호가 있으면 for문을 빠져나감.
				}
			}while(i != j);
			lotto[i] = temp;
		}
		//발생된 로또 번호 출력 (20.33과 20.45는 똑같이 20으로 중복)
		for(int l : lotto) {
			System.out.print(l + "\t");
		}
		System.out.println("\n오름차순");
		//lotto 배열 값을 sort(작은 값부터 차례대로)
		for(i=0 ; i<lotto.length-1 ; i++) {
			for(j=i+1 ; j<lotto.length ; j++) {
			 if(lotto[i] > lotto[j]) {
				 temp = lotto[i];
				 lotto[i] = lotto[j];
				 lotto[j] = temp;
			 		}//if i>j
			 	}//for-j
			}//for-i
		for(int l : lotto) {
			System.out.print(l + "\t");
		}
	}//main
}//class

🎈 Scanner

  • Scanner : 키보드에서 타이핑하는 문자열 또는 입출력 프로그래밍에서 값을 읽어올 때, 무엇인가를 얻어 올 때 사용
Scanner scanner = new Scanner(System.in);
		System.out.print("나이 : ");
		int age = scanner.nextInt();
		System.out.println("입력한 나이는 " + age + "살");
		System.out.print("이름 : ");
		String name = scanner.next();           //이름 사이에 space가 있으면 space 앞의 글자만 출력
		System.out.println("입력한 이름은 " + name);
		System.out.print("주소 : ");
		//버퍼에 남아있는 "\n" 을 지우기
		scanner.nextLine();
		String address = scanner.nextLine();   //"\n" 앞의 값을 return 하고 "\n" 뒤는 지운다
		System.out.println("입력한 주소는 " + address);
		System.out.println("끝");
		scanner.close();
  • 결과
나이 : 21
입력한 나이는 21살
이름 : 홍길동
입력한 이름은 홍길동
주소 : 서울 중구
입력한 주소는 서울 중구
끝

- 가위바위보 게임

  • 사용자가 이길 때까지 진행 -> do while 사용
  • 컴퓨터는 임의로 가위바위보 선택
Random random = new Random();
com = random.nextInt(3);
  • 사용자가 입력값 앞뒤로 space를 넣어도 입력값만 인식하기 -> trim()

code

package quiz;

import java.util.Random;
import java.util.Scanner;

public class Quiz1 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Random random = new Random();
		int u, com;
		final int SCISSOR = 0;
		final int ROCK = 1;
		final int PAPER = 2;
		final int NOTHING = 3;

		do {
			com = random.nextInt(3);
			System.out.println("가위, 바위, 보 중 하나를 입력하세요(사용자가 이기면 종료)");
			String uStr = sc.next().trim();
			if (uStr.equals("가위")) {
				u = SCISSOR;
			} else if (uStr.equals("바위")) {
				u = ROCK;
			} else if (uStr.equals("보")) {
				u = PAPER;
			} else {
				u = NOTHING;
				continue;
			}
			if ((u + 2) % 3 == com) {
				printResult(u, com);
				System.out.println("이겼습니다");
			} else if (u == com) {
				printResult(u, com);
				System.out.println("비겼습니다");
			} else {
				printResult(u, com);
				System.out.println("졌습니다");
			}

		} while (u==NOTHING || (u + 2) % 3 != com);
		System.out.println("끝");
		sc.close();
	}

	private static void printResult(int u, int com) {
		System.out.println("사용자 : " + ((u == 0) ? "가위" : (u == 1) ? "바위" : "보"));
		System.out.println("컴퓨터 : " + ((com == 0) ? "가위" : (com == 1) ? "바위" : "보"));
	}
}

결과

가위, 바위, 보 중 하나를 입력하세요(사용자가 이기면 종료)
가위
사용자 : 가위
컴퓨터 : 가위
비겼습니다
가위, 바위, 보 중 하나를 입력하세요(사용자가 이기면 종료)
바위
사용자 : 바위
컴퓨터 : 바위
비겼습니다
가위, 바위, 보 중 하나를 입력하세요(사용자가 이기면 종료)
보
사용자 : 보
컴퓨터 : 보
비겼습니다
가위, 바위, 보 중 하나를 입력하세요(사용자가 이기면 종료)
보
사용자 : 보
컴퓨터 : 바위
이겼습니다
끝
profile
씨앗 개발자

0개의 댓글