[ Math 클래스 ]
: 수학 계산에 사용할 수 있는 여러가지 정적 메서드를 제공해주는 클래스
public class MathExample {
public static void main(String[] args) {
// Math.abs(); // 절댓값 리턴
int v1 = Math.abs(-5);
double v2 = Math.abs(-3.14);
System.out.println("v1=" + v1);
System.out.println("v2=" + v2);
// Math.ceil(); // 소수점 올린 값 리턴
double v3 = Math.ceil(5.3);
double v4 = Math.ceil(-5.3);
System.out.println("v3=" + v3);
System.out.println("v4=" + v4);
// Math.floor(); // 소수점 버린 값 리턴
double v5 = Math.floor(5.3);
double v6 = Math.floor(-5.3);
System.out.println("v5=" + v5);
System.out.println("v6=" + v6);
// Math.max(); // 실수형의 최댓값 리턴
int v7 = Math.max(5, 9);
double v8 = Math.max(5.3, 2.5);
System.out.println("v7=" + v7);
System.out.println("v8=" + v8);
// Math.min(); // 실수형의 최솟값 리턴
int v9 = Math.min(5, 9);
double v10 = Math.min(5.3, 2.5);
System.out.println("v9=" + v9);
System.out.println("v10=" + v10);
// 0.0 <= Math.random(); < 1.0
// 0보다 크거나 같고 1보다 작은 실수의 랜덤값 리턴
double v11 = Math.random();
System.out.println("v11=" + v11);
// Math.rint(); // 가까운 정수의 실수값 리턴
double v12 = Math.rint(5.3);
double v13 = Math.rint(5.7);
System.out.println("v12=" + v12);
System.out.println("v13=" + v13);
// Math.round(); // 소수점 반올림한 값 리턴
long v14 = Math.round(5.3);
long v15 = Math.round(5.7);
System.out.println("v14=" + v14);
System.out.println("v15=" + v15);
double value = 12.3456;
double temp1 = value * 100;
long temp2 = Math.round(temp1);
double v16 = temp2 / 100.0;
System.out.println("v16=" + v16);
}
}
public class MathRandomExample {
public static void main(String[] args) {
int num = (int)(Math.random()*6) + 1;
// 0.0 <= Math.random() < 1.0
// 0 <= (int)(Math.random();*6) < 6
// 1 <= (int)(Math.random(); * 6) + 1 < 7
System.out.println("num = " + num);
// num : 1 ~ 6까지의 정수형 랜덤값
}
}
[ Random 클래스 ]
: boolean, int, long, float, double 의 타입인 난수(랜덤값)를 출력하는 메서드들을 제공하는 클래스
* Random 클래스로부터 Random 객체를 생성하는 방법
--> 생성자에 매개값으로 종자값(seed값)을 설정할 수 있는데, 종자값을 설정해주면 계속 같은 난수만 출력된다.
즉, 같은 랜덤값만 나오게 된다.
* Random 클래스가 제공해주는 메서드
import java.util.Arrays;
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
/** 로또번호 자동으로 랜덤하게 뽑는 상황 **/
int[] selectNum = new int[6];
Random random = new Random(5);
// seed값 즉, 종자값을 5로 설정한 것
// 종자값을 설정하면 계속 실행을 해도
//다른 랜덤값으로 변경되지 않고
// 한번 정해진 랜덤값이 계속 똑같이 나오게 된다.
System.out.print("선택된 번호: ");
for(int i = 0; i < 6; i++) {
selectNum[i] = random.nextInt(45) + 1;
System.out.print(selectNum[i] + " ");
}
// random.nextInt()
// int 타입의 랜덤값을 리턴해주는 메서드
// 그 메서드의 매개변수로 오는 종자값을 넣으면
// 0부터 종자값까지의 정수값인 랜덤값이 리턴된다.
// 0 <= random.nextInt(45) < 45
// 1 <= random.nextInt(45) + 1 < 46
System.out.println();
/** 로또 당첨번호 만들기 **/
int[] winningNum = new int[6];
random = new Random(30);
System.out.print("당첨번호: ");
for(int i = 0; i < 6; i++) {
winningNum[i] = random.nextInt(45) + 1;
System.out.print(winningNum[i] + " ");
}
System.out.println();
/** 로또 당첨 여부 **/
Arrays.sort(selectNum);
Arrays.sort(winningNum);
boolean result = Arrays.equals(selectNum, winningNum);
// 각각의 배열에 들어있는 값 비교
System.out.print("로또 당첨 여부: ");
if(result) {
System.out.println("로또 1등에 당첨되셨습니다!!!!");
} else {
System.out.println("다음 기회를 노리세요.");
}
}
}
* Random 클래스 활용한 것들 중 하나 : OTP 단말기 (개인용)
--> (랜덤값 추출해서 만드는 아이)
ex)
// 같은 랜덤값만 출력되기 때문에 고유번호(?) 333444 가 만들어진다.
[ Date 클래스 ]
: 출력하는 그 당시의 날짜와 시간을 표현하는 클래스
Date 클래스에 여러개의 생성자가 선언되어 있지만 대부분 비권장(Deprecated)되어서 현재는 Date( ) 기본 생성자만 주로 사용된다.
import java.text.*;
import java.util.*;
public class DateExample {
public static void main(String[] args) {
Date now = new Date();
// 현재 시간과 날짜 반환
String strNow1 = now.toString();
System.out.println(strNow1);
// Tue Nov 29 16:38:47 KST 2022 출력
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 HH:mm:ss");
// HH --> 24시 기준으로 시간 설정
// hh --> 오전 오후 나뉘어서 시간 설정
String strNow2 = sdf.format(now);
// 시간과 날짜 출력하는 형식 바꾸는 메서드..?
System.out.println(strNow2);
// 2022년 11월 29일 16:38:47 출력 (HH로 지정했을 때)
// 2022년 11월 29일 04:38:47 출력 (hh로 지정했을 때)
}
}
>> 코드 부가설명 <<
: Date 클래스로 객체를 만들면 그 객체를 가지고 현재 시간과 날짜를 출력할 수 있다. Date 클래스로 만든 객체로는 미국식으로 시간과 날짜가 출력된다. 그럴때 내가 원하는 형식으로 시간과 날짜를 출력하고 싶다!?
-> SimpleDateFormat 클래스를 사용해서 객체를 만들때 내가 출력하고 싶은 형식으로 지정해주면 내가 원하는 대로 시간과 날짜가 출력된다.
[ Calendar 클래스]
: Calendar 클래스는 달력을 표현한 클래스
Calendar 클래스는 추상 클래스이므로 new 연산자를 사용해서 인스턴스를 생성할 수 없다.
import java.util.*;
public class CalendarExample {
public static void main(String[] args) {
// Calendar now = new Calendar();
// 위처럼 Calendar 클래스로 인스턴스 생성할 수 없다.
// Calendar 객체 생성하는 방법
// 1. Calendar.getInstance();
// Calendar now = Calendar.getInstance();
// 2. Calendar 클래스의 자식 클래스인 GregorianCalendar 객체를 생성하여
// Calendar 타입에 형변환시킨다.
Calendar now = new GregorianCalendar();
// GregorianCalendar 클래스는 윤년을 만드는 클래스
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1;
// Calendar.MONTH : 실제 월에서 -1을 감소한 값이 리턴된다.
// 따라서 1을 더해줘야 내가 원하는 실제 월이 리턴된다.
int day = now.get(Calendar.DAY_OF_MONTH);
int week = now.get(Calendar.DAY_OF_WEEK);
String strWeek = null;
switch(week) {
case Calendar.MONDAY: // 2
strWeek = "월";
break;
case Calendar.TUESDAY: // 3
strWeek = "화";
break;
case Calendar.WEDNESDAY: // 4
strWeek = "수";
break;
case Calendar.THURSDAY: // 5
strWeek = "목";
break;
case Calendar.FRIDAY: // 6
strWeek = "금";
break;
case Calendar.SATURDAY: // 7
strWeek = "토";
break;
default: // 그외 숫자
strWeek = "일";
}
int amPm = now.get(Calendar.AM_PM);
String strAmPm = null;
if(amPm == Calendar.AM) { // 0
strAmPm = "오전";
} else { // 1
strAmPm = "오후";
}
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
System.out.print(year + "년 ");
System.out.print(month + "월 ");
System.out.println(day + "일 ");
System.out.print(strWeek + "요일 ");
System.out.println(strAmPm + " ");
System.out.print(hour + "시 ");
System.out.print(minute + "분 ");
System.out.println(second + "초 ");
}
}
[ 과제_GregorianCalendar 클래스 활용_문제 ]
Q. 키보드를 통해서 연도를 입력 받아 입력 받은 연도가 윤년인지 평년인지를 판별하는 프로그램을 작성하라.
import java.util.GregorianCalendar;
import java.util.Scanner;
public class YearCheck {
public static void main(String[] args) {
System.out.print("연도를 입력 하세요?"); // "2002"
Scanner sc = new Scanner(System.in);
int year = sc.nextInt(); // 2002
// 윤년의 정의 : year % 4 == 0 && year % 100 != 0 || year % 400 == 0
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + "은 윤년");
} else {
System.out.println(year + "은 평년");
}
// GregorianCalendar 클래스의 메서드 중에서 윤년 여부를 체크하는
// 메서드는 isLeapYear() 메서드이다.
// 윤년이면 true 반환, 평년이면 false 반환
System.out.println();
System.out.println("------- GregorianCalendar로 윤년 체크 --------");
GregorianCalendar gc = new GregorianCalendar();
if (gc.isLeapYear(year)) {
System.out.println(year + "은 윤년입니다.");
} else {
System.out.println(year + "은 평년입니다.");
}
}
}
>> 알아두면 좋은 단축키
- ctrl + shift + "F" : 소스코드 자동 정리
'Studying' 카테고리의 다른 글
Rest vs Restful (2) | 2024.01.02 |
---|---|
HTTP 상태 코드 (2) | 2023.10.30 |
클라우드 서비스 개념 공부 (2) | 2023.07.17 |
코딩테스트_SQL공부(업데이트중) (2) | 2023.07.12 |
JPA, MyBatis란 (0) | 2023.07.08 |