java.io.File 클래스

입출력에 필요한 파일 및 디렉터리에 관한 정보를 다를 수 있다.

 

 

list() : 해당 디렉터리의 파일 출력 방법

 

예시

import java.io.*;

public class FileIO {
	public static void main(String[] args) {
		File file = new File("d:\\");
		//디렉토리 파일 출력
		String filelist[] = file.list();
		for (int i = 0; i < filelist.length; i++) {
			System.out.println(filelist[i]);
		}

필자의 D드라이브에는 다음과 같은 파일이 있습니다

 

실행화면 

 숨겨진 파일까지 보이는 것을 확인할 수 있습니다.

$RECYCLE.BIN
File class test
Programs
STUDY
System Volume Information
카카오톡 받은 파일

 

 

 

listFiles() : 해당 디렉터리의 파일 출력 및 파일인지 폴더인지 조사

 

예시

		File filelist2[] = file.listFiles();
		for (int i = 0; i < filelist2.length; i++) {
			if(filelist2[i].isFile()) { // 파일일 경우
				System.out.println("[파일]"+ filelist2[i].getName());
			}else if(filelist2[i].isDirectory()) { // 폴더일 경우
				System.out.println("[폴더]"+ filelist2[i].getName());
			}else {
				System.out.println("[?]"+ filelist2[i].getName());
			}
		}

필자의 D드라이브에는 다음과 같은 파일이 있습니다

 

실행화면

 list()와는 달리 listFiles()는 파일인지 폴더인지 구별하여 출력하여 줍니다.

[폴더]$RECYCLE.BIN
[폴더]File class test
[파일]File class test.txt
[폴더]Programs
[폴더]STUDY
[폴더]System Volume Information
[폴더]카카오톡 받은 파일

 

 

 

createNewFile() : 파일 생성

참고

 해당 메서드는 이름이 같은 파일이 있을 경우 파일을 생성하지 않습니다.

 

예시

		File newfile = new File("d:\\newfile.txt");
		
		try {
			if(newfile.createNewFile()) {
				System.out.println("파일 생성 성공!!");
			}else {
				System.out.println("파일 생성 실패");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		

 

이름이 같은 파일이 없는 경우 실행화면

파일 생성 성공!!

 

mkdirs() : 폴더 생성

참고

 해당 메소드는 이름이 같은 파일이 있을 경우 파일을 생성하지 않습니다.

 하위 디렉터리까지 생성이 가능합니다.

 

예시

		File newDir = new File("d:\\tmp1\\subDir");
		if(newDir.mkdirs()) {
			System.out.println("폴더 생성 성공");
		}else {
			System.out.println("폴더 생성 실패");
		}
		

 

 

 

exists() : 지정한 경로에 디렉터리 & 파일의 존재 여부 확인

 

예시

		if(newfile.exists()) {
			System.out.println("newfile.txt 파일이 존재합니다");
		}

 

 

 

setReadOnly() : 읽기 전용(파일 보존)

 

예시

		newfile.setReadOnly();

 

 

 

delete() : 파일 삭제

 

예시

		newfile.delete();
	}
}

 

 

 

'IT > Java' 카테고리의 다른 글

[자바] 파일 쓰기  (0) 2021.05.26
[자바] 파일 읽기  (0) 2021.05.16
[자바] Calendar Class  (0) 2021.05.13
[자바] String Class  (0) 2021.05.11
[자바] Java 예약어(keyword, reserved word)  (0) 2021.04.24

피보나치 수열이란?

> 처음 두 항을 1과 1로 한 후, 그 다음 항부터는 바로 앞의 두 개의 항을 더해 만드는 수열

     1 1 2 3 5 8 13
     a b c 			--> a+b = c
       a b c			--> a+b = c
         a b c			--> a+b = c

 

import java.util.*;

public class Fibonaci {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		System.out.println("피보나치 수열 계산기!!");
		System.out.print("정수 입력 >> ");
		int num = scn.nextInt();
		// 배열의 숫자가 몇이 들어갈지 모르니 long형으로 잡아준다.
		long a, b, c;	
		long arrNum[] = new long[num];
		
		a = 1;
		b = 1;
		
		arrNum[0] = a;
		arrNum[1] = b;
		
		
		int w = 0;
		while(w < arrNum.length-2) {
			c = a + b;
			arrNum[2 + w] = c;
			
			a = b;
			b = c;
			
			w++;
		}
		// 삼항연산자로 출력문 만들기
		for (long l : arrNum) {
			System.out.print(l +" " );
		}
	}
}

Scanner를 이용한 피보나치 수열 계산기입니다.

피보나치 수열 계산기!!
정수 입력 >> 10
1 1 2 3 5 8 13 21 34 55 

실행화면 입니다.

'문제풀이 > Java' 카테고리의 다른 글

[자바] 문자열을 암호표로 암호화, 복호화  (0) 2021.05.13
[자바] 남은 동전 구하기  (0) 2021.05.12
[자바] (업그레이드) 계산기  (0) 2021.05.12
[자바] 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11

java.util.Calendar 클래스

날짜 시간 -> 일정관리에 주로 사용됩니다.

 

오늘 날짜 보기

참고

 사용 시 주의할 점은 Calendar.MONTH는 기본 설정이 0~11이기 때문에 +1을 해주어야 1~12가 된다.

 

예시

import java.util.*;

public class CalendarClass {
	public static void main(String[] args) {
		
		// Calendar cal = new GregorianCalendar();  ← 객체 생성 가능은하지만 잘 사용하지 않는다.
		
		Calendar cal = Calendar.getInstance();

		// 오늘 날짜 취득(getter)
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;	// 0 ~ 11
		int day = cal.get(Calendar.DATE);
		
		System.out.println(year+"년"+month+"월"+day+"일");

 

실행화면

2021년5월13일

 

 

 

 

 

날짜 지정 방법

참고

 Calendar.MONTH에 날짜 지정 시에는 +1을 할 필요가 없다!

 

예시

		// 날짜 설정(setter)
		cal.set(Calendar.YEAR, 2021);
		cal.set(Calendar.MONTH, 4);
		cal.set(Calendar.DATE, 5);
		
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		day = cal.get(Calendar.DATE);
		
		System.out.println(year+"년"+month+"월"+day+"일");

 

실행화면

2021년4월5일

 

 

 

 

 

Calendar.AM_PM : 오전인지? 오후인지?

참고

 'Calendar.AM_PM'메서드에 삼항 연산자를 사용하여 확인한다!

 

예시

		// 오전/오후
		String ampm = cal.get(Calendar.AM_PM) == 0?"오전":"오후";
		//		               (조건)     ?"true":"false"
		System.out.println(ampm);

 

 

 

Calendar.DAY_OF_WEEK : 무슨 요일 인지 확인!

참고

 사용시 주의할 점은 Calendar.DAY_OF_WEEK == 1(일요일) ~ 7(토요일)

 switch ~ case문 사용하였다.

 

예시

		// 요일 1(일) ~ 7(토)
		int weekday = cal.get(Calendar.DAY_OF_WEEK);
		switch(weekday) {
		case 1:
			System.out.println("일요일");
			break;
		case 2:
			System.out.println("월요일");
			break;
		case 3:
			System.out.println("화요일");
			break;
		case 4:
			System.out.println("수요일");
			break;
		case 5:
			System.out.println("목요일");
			break;
		case 6:
			System.out.println("금요일");
			break;
		case 7:
			System.out.println("토요일");
			break;
		}
		
		int lastday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		System.out.println("이번달의 마지막 날:"+lastday);
		
	}
}

 

실행화면

목요일

 

 

 

'IT > Java' 카테고리의 다른 글

[자바] 파일 읽기  (0) 2021.05.16
[자바] File Class  (0) 2021.05.16
[자바] String Class  (0) 2021.05.11
[자바] Java 예약어(keyword, reserved word)  (0) 2021.04.24
[자바] beginning  (2) 2021.04.23

문자열 암호화

조건 

 > 주어진 암호표를 사용하여 암호화시키기

public class Encryption02 {
	public static void main(String[] args) {
		// 문자열 암호화 시키기
		// a ~ z
		char[] abcCode = { '`', '~', '!', '@', '#', '$', '%', '^', '&', 
						   '*', '(', ')', '-', '_', '+', '=', '|', '[',
						   ']', '{', '}', ';', ':', ',', '.', '/' };
		// 0 ~ 9
		char[] numCode = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
		String src = "abc123";
		// 암호화 문자열을 담을 변수
		String result = "";
		
		for (int i = 0; i < src.length(); i++) {
			// 문자열 scr를 char형으로 한개씩 쪼개기
			char c = src.charAt(i);
			// c를 int형으로 강제형변환
			int index = (int)c;
			// 알파벳 암호화
			if(c >= 'a'&& 'z' >= c) {
				// c == 'a' == 97 때문에 -97을 대입한다.
				// ex) abcCode[index-97]; == abcCode[0];
				result += abcCode[index-97];
			// 숫자 암호화	
			}else if(c >= '0'&& '9' >= c) {
				// c == '0' == 97 때문에 -48을 대입한다.
				result += numCode[index-48];
			}
		}
		System.out.println("원본\t: "+src);
		System.out.println("암호화\t: "+result);
원본 	: abc123
암호화 	: `~!wer

실행화면입니다.

 

문자열 복호화

조건

 > 암호화된 문자열을 원래대로 되돌리기

// 위 코드와 이어서

		// 복호화
		// 복호화 문자열을 담을 변수
		String originalCode = ""; 
		
		for (int i = 0; i < result.length(); i++) {
			char c = result.charAt(i);
			// 알파벳 -> 숫자
			int index = 0;
			if(c >= 'a' && 'z' >= c) {
				for (int j = 0; j < numCode.length; j++) {
					  // c == 'w' == 1
					if ( c == numCode[j]) { 
						index = j;
						break;
					}
				}
				index += 48;
				originalCode += (char)index;
			// 특수기호 -> 알파벳 	
			}else {
				for (int j = 0; j < abcCode.length; j++) {
					if ( c == abcCode[j]) {
						index = j;
						break;
					}
				}
				index += 97;
				originalCode += (char)index;
			}
		}
		System.out.println("복호화\t: "+originalCode);
	}
}
원본 	: abc123
암호화 	: `~!wer
복호화	: abc123

전체 코드 실행화면입니다.

'문제풀이 > Java' 카테고리의 다른 글

[자바] 피보나치 수열  (0) 2021.05.14
[자바] 남은 동전 구하기  (0) 2021.05.12
[자바] (업그레이드) 계산기  (0) 2021.05.12
[자바] 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11

 

public class GetCoins {
	public static void main(String[] args) {
		// 큰 금액의 동전을 우선적으로 거슬러 줘야 한다.
		int[] coinUnit = { 500, 100, 50, 10 };
		int money = 2680;
		System.out.println("money\t: " + money + "원");
       		// coinUnit배열의 길이 만큼 for문 진행
		for (int i = 0; i < coinUnit.length; i++) { 
        		// int형 변수(result)를 만들어주고 동전 개수 계산 값을 넣어준다.
			int result = money/coinUnit[i];	
			System.out.println(coinUnit[i]+"원\t: "+result+"개");
            		// money의 값을 나머지로 초기화
			money = money % coinUnit[i];
		}
	}
}


남은 동전 구하기

조건

 > 거스름돈을 몇 개의 동전으로 지불할 수 있는지 계산 
 > 변수 money의 금액을 동전으로 바꾸었을 때 각각 몇 개의 동전이 필요한지 계산 
 > 출력 단, 가능한 적은 수의 동전을 거슬러 주어야 한다.

'문제풀이 > Java' 카테고리의 다른 글

[자바] 피보나치 수열  (0) 2021.05.14
[자바] 문자열을 암호표로 암호화, 복호화  (0) 2021.05.13
[자바] (업그레이드) 계산기  (0) 2021.05.12
[자바] 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11

 

import java.util.Scanner;

public class Calculator {
	public static void main(String[] args) {
		int num1, num2;
		String oper;
		
		// 첫번째 수 입력
		num1 = number_input("첫번째");
		// 연산자를 입력
		oper = operatorInput();
		// 두번째 수 입력 / + 0 무시
		num2 = number_input("두번째");
		// 연산
		int result = processing(num1, num2, oper);
		// 결과 출력
		resultPrint(num1, num2, result, oper);
	}
	// 입력 함수들
	static int number_input(String no) {
				Scanner scn = new Scanner(System.in);
		String str = "";
		while(true) {
			System.out.print(no + "수 > ");
			str = scn.nextLine();
			// 공백확인
			if(str.equals("")== true) {
				System.out.println("숫자만 입력가능(공백x)");
				continue;
			}
			boolean flag = isNumber(str);
			if(flag == true) {
				break;
			}
			System.out.println("숫자만 입력가능(문자x)");
		}
		return Integer.parseInt(str);
	}
	
	static String operatorInput() {
		// 연산자
		Scanner scn = new Scanner(System.in);
		String oper;
		while (true) {
			System.out.print("연산기호 입력 (+, -, *, /) >>");
			oper = scn.nextLine();
			if (oper.equals("+") || oper.equals("-") || oper.equals("*") || oper.equals("/")) {
				break;
			} else { // 연산기호가 다른문자가 입력이 되었는지? -> 다시 입력
				continue;
			}
		}
		return oper;
	}
	// 유틸리티 함수 -> 다른곳에서도 사용가능!
	static boolean isNumber(String str) {
		boolean flag = true;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if(c < '0' || c > '9') { // 문자열 확인
				flag = false;
				break;
			}
		}
		return flag;
	}
	// 연산처리 함수
	static int processing(int n1, int n2, String oper) {
		int result = 0;
		switch(oper) {
		case "+" :
			result = n1+n2;
			break;
		case "-" :
			result = n1-n2;
			break;
		case "*" :
			result = n1*n2;
			break;
		case "/" :
			if(n2 == 0) {
				System.out.println("'0'은 연산불가!");
			}else {
				result = n1/n2;
				break;
			}
		}
		return result;
	}
	// 결과 출력
	static void resultPrint(int n1, int n2, int result, String oper) {
		System.out.println(n1 +" "+oper+" "+n2+" = "+ result);
	}
}

메소드 사용해서 계산기 프로그램 만들기!

 

'문제풀이 > Java' 카테고리의 다른 글

[자바] 문자열을 암호표로 암호화, 복호화  (0) 2021.05.13
[자바] 남은 동전 구하기  (0) 2021.05.12
[자바] 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 배열 순차 정렬  (0) 2021.05.11
import java.util.*;

public class Calculator {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		
		String str1, str2; // 문자열 첫번째 수, 두번째 수
		int num1, num2; // 정수형 첫번째 수, 두번째 수 
		String oper; // 연산자
		
		// 첫번째수
		while(true) {
			System.out.print("첫번째 수 > ");
			str1 = scn.nextLine();
			// 공백확인
			if(str1.equals("")== true) {
				System.out.println("숫자만 입력가능(공백x)");
				continue;
			}
			boolean flag = true;
			for (int i = 0; i < str1.length(); i++) {
				char c = str1.charAt(i);
				if(c < '0' || c > '9') { // 문자열 확인
					flag = false;
					break;
				}
			}
			if(flag == true) {
				break;
			}
			System.out.println("숫자만 입력가능(문자x)");
		}
		// 연산자
		while(true) {
			System.out.print("연산기호 입력 (+, -, *, /) >>");
			oper = scn.nextLine();
			if(oper.equals("+") || oper.equals("-") || oper.equals("*") || oper.equals("/")) {
				break;				
			} else { 		// 연산기호가 다른문자가 입력이 되었는지? -> 다시 입력

				continue;
			}
		}	
		// 두번째 수
		while(true) {
			System.out.print("두번째 수 > ");
			str2 = scn.nextLine();
			// 공백확인
			if(str2.equals("") == true) {
				System.out.println("숫자만 입력가능(공백x)");
				continue;
			}
			if(oper.equals("/")) {
				if(str2.equals("0")) { // 연산자 '/' -> 0 다시입력
					System.out.println("0으로는 연산불가!");
					continue;
				}
			}
			boolean flag = true;
			for (int i = 0; i < str2.length(); i++) {
				char c = str2.charAt(i);
				if(c < '0' || c > '9') { // 문자열 확인
					flag = false;
					break;
				}
			}
			if(flag == true) {
				break;
			}
			System.out.println("숫자만 입력가능(문자x)");
		}
		num1 = Integer.parseInt(str1);
		num2 = Integer.parseInt(str2);
		// 결과출력
		switch(oper) {
		case "+" :
			System.out.println(num1+oper+num2+"="+(num1+num2));
        		break;
		case "-" :
			System.out.println(num1+oper+num2+"="+(num1-num2));
            		break;
		case "*" :
			System.out.println(num1+oper+num2+"="+(num1*num2));
            		break;
		case "/" :
			System.out.println(num1+oper+num2+"="+(num1/num2));
            		break;
		}
	}
}

 

'문제풀이 > Java' 카테고리의 다른 글

[자바] 남은 동전 구하기  (0) 2021.05.12
[자바] (업그레이드) 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 배열 순차 정렬  (0) 2021.05.11
[자바] 로또 번호 생성  (0) 2021.05.10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class Test {
    Random random = new Random();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int  com, draw, win, lose, round;
    String temp, user;
    void com(){
    	// 0 ~ 3
        com = random.nextInt(3)+1;
    }
    // com의 랜덤 숫자를 String변환
    void comString() {
        if(com == 1){
            temp = "가위";
            pln("Conputer: "+temp);
        }else if(com == 2 ){
            temp = "바위";
            pln("Conputer: "+temp);
        }else if(com == 3){
            temp = "보";
            pln("Conputer: "+temp);
        }
    }
    // user입력
    void user() {
        pln("입력해주세요: ");
        try {
            user = br.readLine();
            pln("user: "+ user);
        } catch (IOException e) {}
    }
    // 게임진행 round
    void round() { 
        while (true) {
            p("몇판을 진행할까요 ? ");
            try {
                round = Integer.parseInt(br.readLine());
                break;
            } catch (NumberFormatException ne) {
                pln("숫자만 입력해주세요.!");
                continue;
            } catch (IOException e) {
            } 
        }
    }
    void figth(){
        pln("round: "+round);
        for(int i=0; i<round; i++) {
            user();
            com();
            comString();
            if(temp.equals("가위")) {
                if(user.equals("가위")) {
                    pln("draw");
                    draw++;
                }else if(user.equals("바위")) {
                    pln("win");
                    win++;
                }else if(user.equals("보")) {
                    pln("lose");
                    lose++;
                }else {
                    pln("가위,바위,보만 내주세요");
                    i--;
                }
            }
            if(temp.equals("바위")) {
                if(user.equals("가위")) {
                    pln("lose");
                    lose++;
                }else if(user.equals("바위")) {
                    pln("draw");
                    draw++;
                }else if(user.equals("보")) {
                    pln("win");
                    win++;
                }else {
                    pln("가위,바위,보만 내주세요");
                    i--;
                }
            }
            if(temp.equals("보")) {
                if(user.equals("가위")) {
                    pln("win");
                    win++;
                }else if(user.equals("바위")) {
                    pln("lose");
                    lose++;
                }else if(user.equals("보")) {
                    pln("draw");
                    draw++;
                }else {
                    pln("가위,바위,보만 내주세요");
                    i--;
                }
            }
        }
        if((draw >= lose) || (draw >= win) || (lose == win)) {
            pln("결과는 ? draw: "+ draw);
        }else if((win >lose) || (win>draw)) {
            pln("결과는 ? win: "+ win);
        }else if((lose > win) || (lose > draw)){
            pln("결과는 ? lose: "+ lose);
        }
    }
    void pln(String str){
        System.out.println(str);
    }
    void p(String str) {
        System.out.print(str);
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.pln("컴퓨터 vs 나 가위바위보 게임!!!!");

        t.round();
        t.pln("===========GAME START!!==========");
        t.figth();
    }
}

 

 

가위바위보 게임

 

 

필자는 자바 공부 중인 학생입니다.

많이 부족한 초보입니다.

피드백해주시면 감사히 받아들이겠습니다.

'문제풀이 > Java' 카테고리의 다른 글

[자바] (업그레이드) 계산기  (0) 2021.05.12
[자바] 계산기  (0) 2021.05.12
[자바] 배열 순차 정렬  (0) 2021.05.11
[자바] 로또 번호 생성  (0) 2021.05.10
[자바] Baseball Game  (0) 2021.05.10
import java.util.*;

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

		Scanner scn = new Scanner(System.in);
		System.out.print("정렬 갯수 > ");
		int line = scn.nextInt();
		int [] arr = new int [line];

		for (int i=0; i<arr.length; i++) {
			System.out.print((i+1)+"번째 숫자를 입력 > ");
			int num = scn.nextInt();
			arr[i] = num;
		}
		System.out.println(Arrays.toString(arr));

		int temp;
		while(true) {
			System.out.println("정렬 순서를 정하세요 : 1.오름 2.내림");
			int order = scn.nextInt();
			if (order == 1) { // 오름차순
				for (int i = 0; i < arr.length - 1; i++) {
					for (int j = i + 1; j < arr.length; j++) {
						if (arr[i] > arr[j]) {
							temp = arr[i];
							arr[i] = arr[j];
							arr[j] = temp;
						}
					}
				}
				break;
			} else if (order == 2) { // 내림차순
				for (int i = 0; i < arr.length - 1; i++) {
					for (int j = i + 1; j < arr.length; j++) {
						if (arr[i] < arr[j]) {
							temp = arr[i];
							arr[i] = arr[j];
							arr[j] = temp;
						}
					}
				}
				break;
			} else {
				System.out.println("1 또는 2로 선택해주세요.");
				continue;
			}
		}
		System.out.println(Arrays.toString(arr));
	}
}

배열 순차 정렬 프로그램

 

 

 

'문제풀이 > Java' 카테고리의 다른 글

[자바] 계산기  (0) 2021.05.12
[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 로또 번호 생성  (0) 2021.05.10
[자바] Baseball Game  (0) 2021.05.10
[자바] 숫자 맞추기 UP&DOWN  (0) 2021.05.10

java.lang.String 클래스

문자열을 사용할 때 주로 사용하는 클래스입니다.

 

 

String Class의 선언 방법

참고

 본래는 클래스를 불러오는 것이기 때문에 인스턴스를 생성하여 불러와야 하지만,

 ex) String str1 = new String("Hello");

 String str1 = "Hello"; 와 같이 선언을 하는 것이 가능하다! (자주 사용하기 때문에)

 

예시

import java.util.*;

public class MainClass {
	public static void main(String[] args) {
    
		String str;
		str = "Hello";
		System.out.println(str);
        
		String str1 = new String("Hello"); // == String str1 = "Hello";
		str1 = "hi";
		String str2 = "반갑습니다";
		System.out.println(str1);
 

 

실행화면

Hello
hi

 

 

 

concat : 문자열 연결

참고

 concat이란 메서드가 있긴 하지만 + 만으로도 연결이 가능하기에 잘 사용하지 않습니다.

 

예시

		String str3 = str.concat(str2);
		System.out.println(str3);
		String str4 = str+str2;
		System.out.println(str4);

 

실행화면

Hello반갑습니다
Hello반갑습니다

 

 

 

equals : 비교

참고

 ==으로 비교시는 false이기 때문에  "다른 문자열입니다"란 문구가 실행될 것입니다.

 이는 ==은 초창기 값으로 비교를 하기 때문입니다.

 그래서 문자열 비교시 equals를 사용합니다.

 

예시

		String str4 = "world";
		String str5 = "worl";
		
		str5 = str5 + "d";
		
		// if(str4 == str5) { // == 초창기 값으로 비교
		if(str4.equals(str5) == true) { // == true 생략가능
			System.out.println("같은 문자열입니다");
		}else {
			System.out.println("다른 문자열입니다");
		}

 

 

 

indexOf, lastIndexOf : 문자의 위치 탐색

참고

 indexOf : 앞부분의 해당 문자열 위치를 탐색

 lastIndexOf : 뒷부분의 해당 문자열 위치를 탐색

 

예시

		String str6 = "abcdabcdabcd";
		//	       01234
		int index = str6.indexOf('c');
		System.out.println("index : "+ index);
		
		int lastIndex = str6.lastIndexOf('c');
		System.out.println("lastIndex : "+ lastIndex);

실행화면

index : 2
lastIndex : 10

 

 

 

length() : 문자열의 길이

 

예시

		int len = str6.length();
		System.out.println("length : "+ len);

 

 

 

replace : 수정

 

예시

		String str7 = "A*B*C*D";
		String rep = str7.replace("*", "-");
		System.out.println("replace : "+ rep);

 

실행화면

replace : A-B-C-D

 

 

 

split : 문자열을 원하는 구분자(token)로 분리

참고

 지정한 구분자로 문자열을 나눠 배열에 저장합니다.(공백 문자열 포함)

 

예시

		/*
			aaaa-bbb-cc		'-' == token(여러가지가 있는데 안되는 것도 있다.)
			aaaa
			bbb
			cc
			1001-홍길동-24-서울시
			1001
			홍길동
			24
			서울시
		*/
		String str8 = "1001-홍길동-24-서울시";
		
		String split[] = str8.split("-");
		System.out.println(split.length);
        
		// 배열 내용 출력 메소드 Arrays.toString(배열명)
		// import 필수! (import java.util.Arrays)
		System.out.println(Arrays.toString(split));
		
		// foreach문 사용
		for ( String s : split) {
			System.out.println(s);
		}
		

 

실행화면

4
[1001, 홍길동, 24, 서울시]
1001
홍길동
24
서울시

 

 

 

substring : 문자열 잘라내기

참고

 사용시 주의할 사항은 str9.substring(0, 4) 일 경우 잘라내어 지는 문자열은 (index, index-1)이라는 점을 숙지하여야 한다.

 

예시

		String str9 = "abcdefghij";
		String str10 = str9.substring(0, 4); // 0 ~ 3
		System.out.println("str10 : "+ str10);
		
		str10 = str9.substring(5); // 5 ~ 끝까지
		System.out.println("str10 : "+ str10);

 

실행화면

str10 : abcd
str10 : fghij

 

 

 

toUpperCase : 대문자로 변환 , toLowerCase : 소문자로 변환

 

예시

		String str11 = "abcDEF";
		System.out.println(str11.toUpperCase()); // 대문자
		System.out.println(str11.toLowerCase()); // 소문자

 

실행화면

ABCDEF
abcdef

 

 

 

trim : 문자열의 앞뒤공백을 삭제

 

예시

		String str12 = " java  java        java   ";
		System.out.println(str12.trim());

 

실행화면

java  java        java

 

 

 

charAt : index를 입력하면 그 위치에 문자를 돌려주는 함수

참고

 문자열인지 숫자인지 확인할 경우 많이 사용되는 메서드이다.

 

예시

		String str13 = "가나다라마바사";
		char c = str13.charAt(3);
		System.out.println("c = "+ c);

 

실행화면

c = 라

 

 

 

contains - 문자열 탐색(있느냐? 없느냐?)

 

예시

		String str14 = "서울시 마포구 서교동";
		
		boolean b = str14.contains("마포");
		System.out.println(b);
	}
}

 

실행화면

true

'IT > Java' 카테고리의 다른 글

[자바] File Class  (0) 2021.05.16
[자바] Calendar Class  (0) 2021.05.13
[자바] Java 예약어(keyword, reserved word)  (0) 2021.04.24
[자바] beginning  (2) 2021.04.23
[자바] MultiThread  (0) 2021.04.22

+ Recent posts