부트캠프(Java)

자바/스프링 부트캠프 12일차(API

동곤일상 2025. 2. 17. 17:15
반응형


1)API

 

1) java.lang

   1-1) String

   1-2) StringBuffer ,  StringBuilder

   1-3) Math

   1-4) Wrapper

   1.5) 정리

 

2) java.utils

 

 

 

 

 

 

 

 

 


2025.02.14 - [AWS활용 자바 부트캠프] - 자바 / 스프링 부트캠프 11일차( 예외처리 , API)

 

자바 / 스프링 부트캠프 11일차( 예외처리 , API)

1) 예외처리  1-1) finally  1-2) thorws   1-3)throw   1-4) 오버라이딩에서의 예외처리   1-5) 체크예외와 언체크예외 생성 2) API          2-1) java.lang 패키지          2-1.1) Object          2-1.2) String

ddkk1120.tistory.com

 

@@ 1-1) String @@

 

저번에 이어서 String클래스에 대해 더 알아보자

 

String문자열의 기능들

 

subString() , trim() , split, toCharArray 등

package ex3_String;

public class StringEx4 {
	public static void main(String[] args) {
		String str = "This is a String";
		//subString () : 부분 문자열
		//subString(5) : 5번 인덱스 이후의 부분문자열
		System.out.println(str.substring(5));
		System.out.println(str.substring(5,10));
		
		System.out.println(str.toUpperCase());
		System.out.println(str.toLowerCase());
		
		str = "   문자열 trim 메서드    ";
		System.out.println(str);
		System.out.println(str.trim());
		System.out.println("str.trim().length() : "+str.trim().length());
		System.out.println("str.length() : "+str.length());
		
		str = "홍길동,이몽룡,김삿갓,abc";
		//split(분리 기준 문자열): 문자열을 기준문자열로 나누어 배열로저장
		String[] split = str.split(",");
		for (String string : split) {
			System.out.println(string);
		}
		
		//문자열을 한개의 char로 분리해 배열로리턴
		char[] cArray = str.toCharArray();
		for (char c : cArray) {
			System.out.print("["+c+"]");
		}
		System.out.println();
		
		str = "abcdefghiz"; //소문자의아스키코드 97~122  대문자 : 65~80
		byte[] barr = str.getBytes();
		for (byte b : barr) {
			System.out.print(b+",");
		}System.out.println();	
	}
}

is a String

is a

THIS IS A STRING

this is a string

         문자열 trim 메서드

문자열 trim 메서드

str.trim().length() : 12

str.length() : 19

홍길동

이몽룡

김삿갓

abc

[홍][길][동][,][이][몽][룡][,][김][삿][갓][,][a][b][c]

97,98,99,100,101,102,103,104,105,122,

 

 


 

 String.format() : 형식화된 문자 (서식문자)를 이용하여 문자열로 리턴

 클래스메서드 --> 객체화필요X

 

 형식문자(서식문자) : %d , %f , %c , %s ...

 System.out.printf(); 사용법 동일

 

package ex3_String;

public class StringEx5 {
	public static void main(String[] args) {
		
		String sf = String.format("%d", 12345);
		System.out.println(sf);
		
		//%d : 10진 정수 decimal
		// %,d : 세자리마다 , 표시
		System.out.println(String.format("%,d", 12345));
		
		// %,10d : 10자리를 확보 후 (3자리마다 , 표시)
		System.out.println(String.format("%,10d", 12345));
		
		// %-10d : 10자리를 확보 후 (좌측정렬)
		System.out.println(String.format("%-10d", 12345));
		
		// %-,10d : 10자리를 확보 후 (좌측정렬) 세자리마다 ,
		System.out.println(String.format("%-,10d", 12345));
		
		// %010d : 10자리를 확보 후 빈자리는 0 으로 채워
		System.out.println(String.format("%010d", 12345));
		
		//%X(대문자) ,  %x(소문자) : 16진정수 . Hexa
		System.out.println(String.format("%X,%x",255,255));
		
		//%o : 8진정수 octal
		System.out.println(String.format("%o", 12));
		
		//%b : 2진정수 binary
		System.out.println(String.format("%b,%b", false,true));
		
		//%f : 부동소수점 float
		//%.2f : 소숫점이하 2자리로출력 (반올림)
		System.out.println(String.format("%.2f", 1.446));
		
		//"%,15.2f" :  15자리를 확보 후 소수점2자리까지만표현 ,  세자리마다 , 표시
		System.out.println(String.format("%,15.2f", 12345.145));
		
		//"%-,15.2f" :  15자리를 확보 후 소수점2자리까지만표현 ,  세자리마다 , 표시 (좌측정렬)
		System.out.println(String.format("%-,15.2f", 12345.145));
		
		//"%015.2f" :  15자리를 확보 후 소수점2자리까지만표현 남은건 0 으로채우기 [, - ]표시불가
		System.out.println(String.format("%015.2f", 12345.145));
		
		
		//%s 문자열출력
		System.out.printf("%s\n","홍길동");
		//%10s : 10자리확보해 문자열출력
		System.out.printf("%10s\n","홍길동");
		//%-10s : 10자리확보해 문자열출력(좌측정렬)
		System.out.printf("%-10s\n","홍길동");
		System.out.printf("%.2s\n","홍길동");//2개문자만
		
		
		//%c : 문자출력
		System.out.printf("%c\n",'홍');
		
		//%5c : 5자리확보해 문자
		System.out.printf("%5c\n",'홍');
		
		//여러개의 자료형 출력
		System.out.printf("%s의 학점은 %c 입니다 . 점수는 %d입니다 \n","동곤유",'A',97);	
	}

}
12345
12,345
    12,345
12345     
12,345    
0000012345
FF,ff
14
false,true
1.45
      12,345.15
12,345.15      
000000012345.15
홍길동
       홍길동
홍길동       
홍
    홍
동곤유의 학점은 A 입니다 . 점수는 97입니다

@@ 1-2 ) StringBuffer ,  StringBuilder @@

 

* StringBuffer , StringBuilder클래스 : 동적문자열

   -- 같은메서드를 멤버로가짐

StringBuffer : 기존클래스 , 스레드의 동기화

 StringBuilder : jdk 5.0이후에 사용가능한 클래스, 스레드의 비동기화

 

  -- equals메서드가 오버라이딩 되어있지않음 . 내용비교안됨 

      ==> 내용비교를 위해서는 String객체로 변경해서 비교

- 동적 문자열 . String클래스의 보조클래스로 사용함

 

public class StringBufferEx1 {
	
	public static void main(String[] args) {
		StringBuffer sb1 = new StringBuffer("abc");
		StringBuffer sb2 = new StringBuffer("abc");
		//StringBuilder로 써도상관없음
		
		System.out.println("sb1==sb2 : "+(sb1==sb2));//같은객체냐?
		
		//equals() : 내용비교를 위해 오버라이딩 X
		System.out.println("sb1.equals(sb2) : "+(sb1.equals(sb2)));
		
		//내용비교를 위해서는 문자열반환이 필요
		System.out.println("sb1.toString().equals(sb2.toString()) : "+
				(sb1.toString().equals(sb2.toString())));
		
		
		
		System.out.println("@@ String Builder @@");
		StringBuilder sb3 = new StringBuilder("ABC");
		StringBuilder sb4 = new StringBuilder("ABC");
		System.out.println("sb3==sb4 : "+(sb3==sb4));//같은객체냐?
		
		System.out.println("sb3.equals(sb4) : "+(sb3.equals(sb4)));
		
		System.out.println("sb3.toString().equals(sb4.toString()) : "+
				(sb3.toString().equals(sb4.toString())));

        
	}
}

sb1==sb2 : false

sb1.equals(sb2) : false

sb1.toString().equals(sb2.toString()) : true

 

 

@@ String Builder @@

 

sb3==sb4 : false

sb3.equals(sb4) : false

sb3.toString().equals(sb4.toString()) : true

 


 


 * StringBuffer클래스의 주요메서드
 * sb : abc123Afalse

package ex4_stringbuffer;

public class StringBufferEx2 {
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		sb.append("abc").append(123).append('A').append(false);
		System.out.println("sb : "+sb);//abc123Afalse
		
		sb.delete(2, 4);//2,3번인덱스제거  ab23Afalse
		System.out.println(sb);
		
		sb.deleteCharAt(4);//4번인덱스 제거 delete(4,5)와동일
		//ab23false
		System.out.println(sb);
		
		sb.insert(4, "=="); //4번인덱스에 == 삽입
		//ab23==false
		System.out.println(sb);
		
		System.out.println("sb = new StringBuilder(\"ABCDEFG\");");
		sb = new StringBuilder("ABCDEFG");//sb의 참조값변경
		System.out.println("sb : "+sb);
		
		sb.replace(0, 3, "abc");//012번인덱스 abc로치환
		System.out.println(sb);//abcDEFG
		
		sb.reverse();//역순
		System.out.println("sb.reverse() : "+sb);
		
	}
}

sb : abc123Afalse

ab23Afalse

ab23false

ab23==false

sb = new StringBuilder("ABCDEFG");

sb : ABCDEFG

abcDEFG

sb.reverse() : GFEDcba

 

 


string.cotains(charSequence)

string에 charSqeunce를 포함하고 있는가?

여기서는 string.charAt(i)로 문자열(char)을 뽑은 후

+""을 해줌으로써 String형으로 만들어서  contains()안에 들어갈 수 있게되는것임!!

package ex4_stringbuffer;

public class Exam1 {
	public static void main(String[] args) {
		System.out.println(delchar("(1!2@3$4~5)","~!@#$%^&*()"));//12345
		System.out.println(delchar("(1!2@3$4~5)","12345"));//!@$~
	}

	private static String delchar(String string, String string2) {
		StringBuilder sb = new StringBuilder();
		String s = new String();

		for (int i = 0; i < string.length(); i++) {
			//string2의인덱스에 string이 존재하지않는다면 append
//			if(string2.indexOf(string.charAt(i))<0) {
//				sb.append(string.charAt(i));
//			}
			if(!string2.contains(string.charAt(i)+"")){
				s+=string.charAt(i);
			}
		}
		
		return s;
	}

}

12345

(!@$~)

 


@@ 1-3) Math 클래스 @@

 * Math클래스
 * 
 * 생성자의 접근제한자 prviate(객체생성불가능
 * 모든멤버가 static인 클래스
 * - 두개의상수
 * Math.PI :  원주율
 * Math.E : 자연로그
 

package ex5_Math;


public class MathEx1 {
	public static void main(String[] args) {
		//abs() 절대값
		System.out.println(Math.abs(5));
		System.out.println(Math.abs(-5));
		System.out.println(Math.abs(3.14));
		System.out.println(Math.abs(-3.14));
		
		//근사정수 : ceil(큰) , floor(작은) , rint
		
		//ceil : 큰 근사정수
		System.out.println(Math.ceil(5.4));//6.0
		System.out.println(Math.ceil(-5.4));
		
		// floor : 작은 근사정수
		System.out.println(Math.floor(5.4));
		System.out.println(Math.floor(-5.4));
		
		//rint : 근사정수
		System.out.println(Math.rint(5.4));
		System.out.println(Math.rint(-5.4));
		
		//최대최소
		System.out.println(Math.max(4, 3));
		System.out.println(Math.max(2, 17));
		System.out.println(Math.min(8, 12));
		System.out.println(Math.min(4.5, 3.21));
		
		//반올림
		System.out.println(Math.round(5.4));
		System.out.println(Math.round(5.5));
		
		//난수 : random 
		System.out.println(Math.random()); //0 <= x < 1
		
		//삼각함수 : 각도단위는 Radians
		System.out.println(Math.toDegrees(Math.PI/2));//Math.PI ==180도
		//sin(90도)
		System.out.println(Math.sin(Math.PI/2));
		
		//cos(60도)
		System.out.println(Math.cos(Math.toRadians(60)));
		
		//tan(45도)
		System.out.println(Math.tan(Math.PI/4));
		
		//log함수
		System.out.println(Math.log(Math.E));//logee ==1
		
		//제곱근
		System.out.println(Math.sqrt(9));
		
		//제곱
		System.out.println(Math.pow(10, 3));
	}
}

5

5

3.14

3.14

6.0

-5.0

5.0

-6.0

5.0

-5.0

4

17

8

3.21

5

6

0.7983339731963263

90.0

1.0

0.5000000000000001

0.9999999999999999

1.0

3.0

1000.0

 


 

예제

package ex5_Math;

//round(실수값 , 자리수) 실수값을 반올림해 소숫점이하자리수로 출력
//실수값을 소숫점이하자리수까지출력
public class Exam1 {
	public static void main(String[] args) {
		round(3.1215,1);
		round(3.1215,2);
		round(3.1215,3);
		System.out.println(truncate(3.15345,1));//3.1
		System.out.println(truncate(3.15345,2));//3.15
	}

	private static double truncate(double d, int i) {
		
		double num = Math.pow(10, i);
		return (int)(d*num)/(num) ;
		// (int)31.5345 / 10 == 31/10 == 3.1
	}

	private static void round(double d, int i) {
		double pow = Math.pow(10,i);
		System.out.println(Math.round(pow*d)/pow);
		
		
		String format2 = String.format("%."+i+"f", d);
		System.out.println(format2);	
	}
}

3.1

3.1

3.12

3.12

3.122

3.122

 

3.1

3.15


@@ 1-4) Wrapper 클래스 @@

package ex6_Wrapper;


public class WrapperEx1 {
	public static void main(String[] args) {

		Integer i1 = 100;
		Integer i2 = 100;
		System.out.println(i1==i2);
		System.out.println(100==i1);
		System.out.println(i1.equals(i2));

		//int 정보
		System.out.println("int형의 최댓값 : "+Integer.MAX_VALUE);
		System.out.println("int형의 최소값 : "+Integer.MIN_VALUE);
		System.out.println("int형의 bit 크기 : "+Integer.SIZE);

		//int 정보
		System.out.println("double형의 최댓값 : "+Double.MAX_VALUE);
		System.out.println("double형의 최소값 : "+Double.MIN_VALUE);
		System.out.println("double형의 bit 크기 : "+Double.SIZE);
		
		//정수형 <- 문자열
		//Integer.parseInt(숫자문자열) 
		//Integer.parseInt(숫자문자열,진법) : 해당진법으로 인식해 int형으로 리턴 
		System.out.println(Integer.parseInt("123"));
		System.out.println("\"123\",8 : "+Integer.parseInt("123",8));
		//( 10진수 <- 8)
		System.out.println("\"123\",16 : "+Integer.parseInt("123",16));
		//(10진수 < - 16진수)
		
		System.out.println(Double.parseDouble("123.56"));
		System.out.println(Float.parseFloat("123.56"));

	}
}

true

true

true

int형의 최댓값 : 2147483647

int형의 최소값 : -2147483648

int형의 bit 크기 : 32

double형의 최댓값 : 1.7976931348623157E308

double형의 최소값 : 4.9E-324

double형의 bit 크기 : 64

123

"123",8 : 83

"123",16 : 291

123.56

123.56

 


package ex6_Wrapper;

public class WrapperEx2 {

	public static void main(String[] args) {
		char[] arr  = {'A','a','&','가','0'};
		for(char c : arr) {
			if(Character.isUpperCase(c)) {
				System.out.println(c+" 대문자");}
			if(Character.isLowerCase(c)) {
				System.out.println(c+" 소문자");}
			if(Character.isDigit(c)) {
				System.out.println(c+" 숫자");}
			if(Character.isAlphabetic(c)) {//한글도 문자
				System.out.println(c+" 문자");}
			else {
				System.out.println(c+" 문자 아님");//숫자 or 문자가아닌것
			}
		}
	}
}

A 대문자

A 문자

a 소문자

a 문자

& 문자 아님

가 문자

0 숫자

0 문자 아님

 


Wrapper 예제문제

package ex6_Wrapper;

public class Exam1 {
	public static void main(String[] args) {
		String str = "10,20,   30,  40,  50, 60";
		
	
		
		String[] split = str.split(",");
		int sum=0;
		System.out.println("공백 제거 전");
		for (String s1 : split) {
			System.out.printf("["+s1+"]");
		}System.out.println();
        
        //공백제거를 하지않는다면 NumberFormatException발생
		
		
		for (int i = 0; i < split.length; i++) {
			int num = Integer.parseInt(split[i].trim());
			sum+=num;
			if(i != split.length-1) {
				System.out.print(num+"+");
			}
			else {
				System.out.print(num);
			}
			
		}
		System.out.println(" == "+sum);
	}
}

공백 제거 전 : [10][20][   30][   40][   50][  60]

10+20+30+40+50+60 == 210

 

 



  switch 구문에서 조건값으로 사용할 수 있는 자료형


 * char      byte   short    int        String 
 * 
 * Character Byte  Short   Integer

package ex6_Wrapper;

public class WrapperEx3 {
	public static void main(String[] args) {
		Integer c = 0;
//		Character c = 0;
//		Short c  = 0;
		
		switch(c) {
		case 0 ->System.out.println("하하");
		default -> System.out.println("switch 조건값 테스트");
		}
	}
}

하하

 


@@ 1-5)정리 @@

 

* java.lang 패키지의 클래스

 

* Object : 모든 클래스의 부모 클래스

 

* String : 문자열객체 ,정적인 문자열(불변)

 

* StringBuffer , StringBuilder : 동적인 문자열, equals 메서드 오버라이딩 안됨

 

* Math : 객체화불가능 , 상속불가능 ,모두 클래스멤버임(static) Math.멤버 로 접근

 

* Wrapper : 자료형을 객체화하기위한 클래스 . ,기본자료형과 형변환 가능

(Boolean , Byte , Short , Integer , Long , Character , Float , Double)

 


@@ 2) java.util @@

2-1) Random클래스

 

Random 클래스 : 난수 발생 클래스

* 1.seed 값 설정 기능

* 2. 자료형 별로 난수 발생

 

 nextInt() : 정수형 난수

 nextInt(n) : 정수형 난수(0 <= x < n )

 nextDouble() : 실수형 난수 0 <= x < 1.0

 nextBoolean() : true / false

 

package ex7_random;

import java.util.Random;
public class RandomEx1 {
	public static void main(String[] args) {
		Random random = new Random();
		random.setSeed(System.currentTimeMillis());
		/*
		 * System.currentTimeMillis() :
		 * 1970년부터 지금까지의시간을 밀리초로 리턴
		 * 
		 */
		
		for(int i = 0 ; i<5 ; i++) {
			System.out.println(i+" : "+random.nextInt(100));
		}
		System.out.println("=================");
		
		Random random2 = new Random();
//		random2.setSeed(2);
		//시드 고정(다시실행해도 바뀌지않는다)
		for(int i = 0 ; i<5 ; i++) {
			System.out.println(i+" : "+random2.nextInt(100));
		}
		
		//true/false 난수 발생시키기
		for (int i = 0; i <5 ; i++) {
			System.out.println(i+":"+random2.nextBoolean());
		}
	}
}

0 : 47

1 : 95

2 : 52

3 : 40

4 : 62

=================

0 : 70

1 : 7

2 : 30

3 : 48

4 : 86

 

0:true

1:false

2:true

3:true

4:false


Random 예제

 * true / false 값 난수발생해 시스템과 사용자중 3번연속 true가 나오는 쪽이 승리

package ex7_random;

import java.util.Random;

public class Exam1 {
	public static void main(String[] args) {
		Random sy = new Random();
		Random us = new Random();
		int sCount = 0;
		int uCount = 0;
		
		System.out.println("시스템 \t 사용자");
		while(true) {
			boolean sNum = sy.nextBoolean();
			boolean uNum = us.nextBoolean();
			System.out.printf("%5b\t%5b",sNum,uNum);
			System.out.println();
			sCount= (sNum==true? sCount+1 : 0);
			uCount= (uNum==true? uCount+1 : 0);
            //sCount= (sNum ? sCount+1 : 0);
			//uCount= (uNum ? uCount+1 : 0);
			
			if(sCount==3) {
				System.out.println("@@시스템승리@@");
				break;
			}
			else if(uCount==3) {
				System.out.println("@@사용자승리@@");
				break;
				
			}
		}	
	}
}

시스템 사용자

true false

true false

false false

false false

false true

true true

true false

true false

@@시스템승리@@

 

 


오늘의 문제풀이

 

/* 문자열 1,234를 정수로 변경하여  * 10 한 값을 세자리마다 , 찍어 출력하기 
* [결과]
* 12,340

 

split 으로 , 를기준으로 string배열을 만들어낸 후

모든 요소를 더한 후 반환(String의 더하기)

그 후 Integer.parseInt()로 int형반환 후

String.format을 이용해 3번쨰마다 , 를찍어주고

10을 곱함

package test2;

public class Test2 {
	public static void main(String[] args) {
		String str = "1,234";
		String[] split = str.split(",");
		String s = split[0]+split[1];//1234
		
		int int1 = Integer.parseInt(s);
		String format = String.format("%,d", int1*10);
		//%,d 3번째마다 ,찍기
		System.out.println(format);
	}

}

 


* 다음 결과가 나오도록 정의된 메서드를 구현하기

* 메서드명 : filldash(문자열,길이)

* 기능 : 문자열을 주어진 길이의 문자열로 만들고,

* 왼쪽 빈 공간은 -으로 채운다.

* 만일 주어진 문자열이 null이거나

* 문자열의 길이가 length의 값과 같으면 그대로 반환한다.

* 만일 주어진 length의 값이 0과 같거나 작은 값이면

* 빈 문자열("")을 반환한다.

* 반환타입 : String

* 매개변수 : String src, int length

[결과]

----A12345

 

A12

null

 

public class Test4 {
	public static void main(String[] args) {
		  String src = "A12345";
		  System.out.println(filldash(src, 10));
		  System.out.println(filldash(src, -1));
		  System.out.println(filldash(src, 3));
		  System.out.println(filldash(null, 3));
	}

	private static String filldash(String src, int i) {
		if(src == null) { //src가 null이면 null문자반환
			return "null";
		}
		if(src.length()>i && i>0) {//0< i < src.length() 
			return String.format("%."+i+"s", src);
		}
		else if(src.length()<i) {
			String format = String.format("%"+i+"s", src);
			return format.replace(" ", "-");
            //일단 format으로 원하는 자리수만큼을 만들어준 후
            //빈 칸을 - 로 바꿔줘서 반환함
		}
		else {
			return "";
            //i가 0보다같거나작으면 빈칸 반환
		}
	}
}

----A12345

 

A12

null

 


 * int getRand(f,t) : 함수 구현하기
 *   f ~ t 또는 t~ f 까지  범위에 숫자를 임의의 수로 리턴하는 함수
 *   f, t 값은 포함됨. 
 
[결과]
-2,1,0,-3,-2,1,-1,0,-2,0,0,1,0,-3,0,-1,-1,-2,-2,1,
3,3,0,0,-1,-1,0,3,2,3,0,-1,1,1,-1,3,0,0,1,-1,    

package test2;

import java.util.Random;


public class Test5 {
	public static void main(String[] args) {
		for(int i=0;i<20;i++) {
			System.out.print(getRand(1,-3)+",");
		}
		System.out.println();
		for(int i=0;i<20;i++) {
			System.out.print(getRand(-1,3)+",");
		}
	}

	private static int getRand(int i, int j) {
		Random random = new Random();
		
		if(i>j) {//i가 j 보다 크다면 자리를 바꿔
		return random.nextInt(j, i+1); 
		//j~~i 중에 랜덤한숫자 뽑음
		}
		else {
			int nextInt = random.nextInt(i,j+1);
			return nextInt;
			}
	}
}

1,-2,1,0,-3,-3,0,-2,1,-2,1,1,0,1,-1,-3,-2,-2,-1,-1,

0,2,3,0,2,-1,3,0,3,1,0,-1,3,-1,2,1,-1,0,-1,0,