728x90

이것을 사용하는 이유는

강제 타입변환을 하기전에 구현한 객체가 인터페이스타입으로 변환되어 있는지 확인하기 위해서이다.

쉽게 객체의 타입을 확인하기 위해서 사용하는 메소드이다.
확인을 해서 강제 타입 변환이 가능한지 검사하는데 주로 사용하는 메소드이다.

지식인 글을 보고 더 공부하자

 

https://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040201&docId=136479378&qb=7J6Q67CUIGluc3RhbmNlT2Y=&enc=utf8§ion=kin&rank=2&search_sort=0&spq=0

 

자바 InstanceOf 개념 설명좀 해주세요 ㅠㅠ

package classes;class A { void abc(){ System.out.println("Hello"); // ---> 그리고 이값은 왜 출력이 안되는지하구요 ...

kin.naver.com

 


str = baabbaa
System.out.peintln(str.indexOf("aa", 0));

indexOf는 문자열의 첫번째(0번)부터 내가 원하는 단어("aa")를 찾는다.
저 코드를 실행하면 1이 출력된다.
b a a b b a a
0 1 2 3 4 5 6   의 순서이기 때문이다.
근데 우리가 원하는 aa는 1번째 자리 말고도 5번에도 위치하는데 위의 코드는 첫번째를 찾으면 종료해버린다.
그럼 우리는 다시 3번의 위치부터 검색을 해야한다.

str = baabbaabbaa
System.out.peintln(str.indexOf("aa", 0)); //0부터 찾기 시작해서 1출력
System.out.peintln(str.indexOf("aa", 3)); .//다시 3번부터 찾기 시작해서 5출력
System.out.peintln(str.indexOf("aa", 7)); .//다시 7번부터 찾기 시작해서 9출력

b a a b b a a b b a a
0 1 2 3 4 5 6 7 8 9 10
System.out,println(str.indexOf("aa",0));를 실행하면
0번째인 b부터 시작해서 1번째에 있는 a를 해서 찾았고 1을 출력
그리고 우리는 그 뒤에 있는 aa를 찾아야 하기 때문에 3번 부터 다시 검색하게 만들어야 한다.
System.out,println(str.indexOf("aa",3));을 실행하면
3번째인 b부터 시작해서 5번째에 있는 a을 만나 5를 출력
그리고 또다시 뒤를 찾아야하기 때문에 7번부터 다시 검색.
System.out,println(str.indexOf("aa",7));을 실행하면
7번째인 b부터 시작해서 9번째에 있는 a을 만나 9를 출력

System.out,println(str.indexOf("aa",0)); 1 출력
System.out,println(str.indexOf("aa",3)); 5 출력
System.out,println(str.indexOf("aa",7)); 9 출력

그럼 문제를 보자

문제
문자열을 입력하고 바꾸고싶은 문자열과 바꿀 문자열을 입력한 다음 문자를 바꿔주고
몇번 치환했는지 출력하기
[실행결과]
문자열 입력 : aabba
현재 문자열 입력 : aa
바꿀 문자열 입력 : cc
ccbba
1번 치환

문자열 입력 : aAbbA
현재 문자열 입력 : aa
바꿀 문자열 입력 : cc
ccbba
1번 치환

문자열 입력 : aabbaa
현재 문자열 입력 : aa
바꿀 문자열 입력 : cc
ccbbcc
2번 치환

package class_constructor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StringTest02_0925 {
	private String input, nowWord, changeWord;
	public StringTest02_0925() throws IOException, NumberFormatException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		System.out.print("문자열 입력: ");
		input = br.readLine().toLowerCase();
		System.out.print("현재 문자열 입력: ");
		nowWord = br.readLine().toLowerCase();
		System.out.print("바꿀 문자열 입력: ");
		changeWord = br.readLine();
		while(nowWord.length()>input.length()) {
			System.out.println("처음 입력한 문자열의 크기보다 큽니다.");
			System.out.print("현재 문자열 입력: ");
			nowWord = br.readLine();
			System.out.print("바꿀 문자열 입력: ");
			changeWord = br.readLine();
		}

	}
	public void disp() {
		//문자열이 몇번째에 있는지 검색
		int index =0;
		int count = 0;
		while((index = input.indexOf(nowWord,index)) != -1) {
			//index는 찾는위치를 뜻하는데 index의 숫자는 계속 변해야 하니까
			//str.indexOf(target, index)를 실행하면 처음에 문자가 있는 숫자가 나온다.
			//그리고 그 숫자(위치)가 index가 되서 그 자리부터 다시 검색을 반복(while)
			index += nowWord.length();
			count++;
		}
		System.out.println(input.replace(nowWord, changeWord));
		System.out.println(count+"번 치환");
		}	
	
	public static void main(String[] args) throws IOException,NumberFormatException{
		while(true) {
			StringTest02_0925 st = new StringTest02_0925();
			st.disp();
		}
	
	}

}

처음에 출력해줄 기본 메소드를 입력한다.
근데 사용자가 대문자를 입력해도 오류가 나지 않도록 toLowerCase()메소드를 통해 
사용자가 입력한 대문자를 소문자로 치환해 input에 저장한다.

그리고 바꿀 문자열 changWord다음에 입력한 문자열 보다 바꿀 문자열이 더 큰 문자열을 인식하지 못하게 범위를 지정해준다.
입력한 문자열(input)보다 현재 문자열(nowWord)가 크면 인식을 할 수 없기 때문에 올바르게 입력할때까지 while문으로감싼다.

 

public class StringTest02_0925 {
	private String input, nowWord, changeWord;
	public StringTest02_0925() throws IOException, NumberFormatException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		System.out.print("문자열 입력: ");
		input = br.readLine().toLowerCase();
		System.out.print("현재 문자열 입력: ");
		nowWord = br.readLine();
		System.out.print("바꿀 문자열 입력: ");
		changeWord = br.readLine();
		while(nowWord.length()>input.length()) {
			System.out.println("처음 입력한 문자열의 크기보다 큽니다.");
			System.out.print("현재 문자열 입력: ");
			nowWord = br.readLine();
			System.out.print("바꿀 문자열 입력: ");
			changeWord = br.readLine();
		}

	}
	

a그다음 이 문제에서 가장 중요한 문자열을 검색해서 치환하는 코드이다.
몇번 치환해 주는지 갯수를 세는 count와 
바꾸고싶은 문자열이 몇번째에 있는지 알아내기 위한 index를 필드로 선언해준다.

문자를 변환하는거는 String클래스에 있는 replace(char oldChar, char newChar) 메소드를 사용하면 쉽다.

public void disp() {
		//문자열이 몇번째에 있는지 검색
		int index =0;
		int count = 0;
		while((index = input.indexOf(nowWord,index)) != -1) {
			//index는 찾는위치를 뜻하는데 index의 숫자는 계속 변해야 하니까
			//str.indexOf(target, index)를 실행하면 처음에 문자가 있는 숫자가 나온다.
			//그리고 그 숫자(위치)가 index가 되서 그 자리부터 다시 검색을 반복(while)
			index += nowWord.length();
			count++;
		}
		System.out.println(input.replace(nowWord, changeWord));
		System.out.println(count+"번 치환");
		}	
	

문제는 몇번 변환을 했는지 카운트를 세는건데 replace를 사용하면 단계고뭐고 한번에 바꿔버려서 count를 셀수가 없다
그럼  입력한 문자열(input)에 바꾸고싶은문자(nowWord)가 몇개 있는지 찾아봐야 한다.
문장의 끝까지 찾아야 하니깐 while문으로 감싸고 조건문을 넣어줘야 한다.
위에서 봤듯이 indexOf를 사용해 문장에서 내가 바꾸고싶은 "aa"를 검색하면 0번째부터 찾아야한다.
b a a b b a a b b a a
0 1 2 3 4 5 6 7 8 9 10

System.out,println(str.indexOf("aa",0));

이 코드를 실행하면 1이 출력된다.
0번 b부터 시작해서 1번째에 있는 a를 찾아내고 끝이 난다. 내가 찾을려고 한건 "aa"인데 왜 1이 나오냐?
baa에서 1,2번째이기 때문에 시작점인 1이 나온다. (만약 ba를 검색하면 0, 4, 8을 출력해낸다.)
암튼 2까지 우리가 찾는 문자열이니깐 3번째부터 다시 검색을 해보자!

System.out,println(str.indexOf("aa",3)); 

이렇게하면 5를 출력한다. 
근데 자동으로 찾아내야지 우리가 일일히 입력할 수는 없다. 공식을 만들어보자.
우리가 처음시작인 0번째에서 찾았고 그다음 3번째에서 검색을 했다.
그럼 저 자리는 계속 변해야 하니까 index라는 변수를 지정해주자.
그럼 input.indexOf(nowWord, index);가 되는데 우리가 바꾸고 싶은 문자열은 1개일수도 있고 여러개일수도 있다. 그럼 length를 써야겠네?

일단 우리문제에서는 난 aa를 찾아내서 바꿀거다.
처음에 1번째 자리가 출력되고 aa를 지난 3번자리에서 다시 검색을 했다. 1과 3은 2가 차이난다.
그다음 3부터 찾았는데 5가 나오고, 난 다시 7번부터 찾아야 된다. 그럼 5 랑 7은 2가 차이난다.
공통으로 변하는건 내가 바꾸고싶은 문자 aa만큼 2개씩 index가 늘어난다.

index 출력 +=nowWord.length()
0 1 2
3 5 2
7 9 2

이렇게 생각할 수 있겠다.
그럼 index = input.indexOf(nowWord, index);{ 
           index += nowWord.length();
}
라고 공식을 만들 수 있다.
근데 조건에 더이상 발견하지못하면 false가되어 빠져나올 수 있도록 

while((index = input.indexOf(nowWord,index)) != -1)를 해준다.
indexOf조건에 맞는게 나오면 위처럼 0,1,5,9 이런게 나와서 -1이 아니면 true
indexOf의 조건에 맞지 앉으면 -1이 출력되는데 그럼 -1이랑 같으니까 !=는 false가 되어 탈출.

public static void main(String[] args) throws IOException,NumberFormatException{
		while(true) {
			StringTest02_0925 st = new StringTest02_0925();
			st.disp();
		}
	
	}

마지막으로 출력하면된다...

728x90

'JAVA' 카테고리의 다른 글

DecimalFormat(숫자 형식 클래스)  (0) 2020.10.01
가변인자 varArgs  (0) 2020.09.29
Import Static  (0) 2020.09.28
배열 연습문제 05  (0) 2020.09.24
상속  (0) 2020.09.24
728x90
문제
x, y값 입력받고 x의 y승 구하기
무한 반복하게 만들기
package loop;

import java.util.Scanner;

public class ForTest05 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int x, y;

		while (true) {
			int mul = 1; // 이게 반복문 안에 있어야지 끝날때마다 초기화가 가능.
			System.out.println("거듭제곱을 구하세요");
			System.out.println("x의 y승을 계산하시오");

			System.out.print("x값 입력 : ");
			x = sc.nextInt();
			System.out.print("y값 입력 : ");
			y = sc.nextInt();

			for (int i = 1; i <= y; i++) {
				mul *= x;
			}
			System.out.println(x + "의 " + y + "승 " + mul);
			System.out.println();
		}

	}
}

System.in.read() 사용하는 방법
read는 숫자가 아닌 문자로 읽기 때문에 
숫자로 입력을 해도 아스키코드로 인식을 한다. 그래서 입력값에 -48을 해줘야지 사용자가 원하는 값을 입력할 수 있다.

package loop;

import java.io.IOException;

//System.in.read(); 사용한 방법
public class ForTest05_2 {
	public static void main(String[] args) throws IOException {

		while (true) {
			System.out.print("x값 입력 : ");
			int x = System.in.read() - 48;// 숫자가 아닌 문자로 읽기 때문에 0의 아스키값을 빼줘야함
			System.in.read(); // 엔터값까지 입력하기 때문에 buffer에 입력값을 지우기 위해 추가
			System.in.read();

			System.out.print("y의 값 입력 : ");
			int y = System.in.read() - '0';
			System.in.read();
			System.in.read();

			int mul = 1;
			for (int i = 1; i <= y; i++) {
				mul *= x;
			}
			System.out.println(x + "의 " + y + " 승은 " + mul);
			System.out.println();
		}
	}

}
728x90

'JAVA' 카테고리의 다른 글

배열 연습문제04  (0) 2020.09.12
배열, 2차원 배열 정리  (0) 2020.09.12
숙제-더하기 연습 프로그램(for, 중첩for, while, bufferedReader,  (0) 2020.09.09
숙제-NumberGame(bufferedReader, while, if )  (0) 2020.09.09
switch 연습02  (0) 2020.09.08
728x90
문제
더하기 연습 프로그램
10~99 사이의 난수를 2개(a, b) 발생하여 합을 구하는 프로그램
문제수는 총 5문제를 제공한다 - for
1문제당 점수 20점씩 계산

[실행결과]
[1] 25 + 36 = 45
틀렸다

[2] 78 + 10 = 88
딩동뎅
...

[5] 12 + 25 = 37
딩동뎅

당신의 총 x문제를 맞추어서 xx점 입니다
package loop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AddGame {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int user, com1, com2, sum, count = 0, result = 0;

		for (;;) {//for1
			for (int i = 1; i <= 5; i++) {//for2
				com1 = (int) (Math.random() * 89) + 10;
				com2 = (int) (Math.random() * 89) + 10;

				System.out.print("[" + i + "] " + com1 + " + " + com2 + " = ");
				user = Integer.parseInt(br.readLine());
				result = com1 + com2;

				if (result == user) {
					System.out.println("딩동댕");
					count++;
				} else {
					System.out.println("틀렸다. 답 : " + result);
				}
			} // for2
			sum = count * 20;
			System.out.println("당신은 총" + count + "문제를 맞춰서 " + sum + "점 입니다.");
			
			String user1;
			while (true) {//while
				System.out.println("continue Y/N : ");
				user1 = br.readLine();

				if (user1.equals("n") || user1.equals("N") || user1.equals("y") || user1.equals("Y"))
					break; // 저 4개의 문자를 받으면 while문을 break해서 나가기 

			} // while
			//나갔는데 아래처럼 n이 아니면 break를 하지 안고 다시 for2로 올라감
			if (user1.equals("n") || user1.equals("N"))
				
			break;	
		}//for1
		System.out.println("프로그램 종료");
	}

}

 난수 2개를 생성하고 값을 저장해야하니까 com1, com2를 만든다.
전체를 무한반복하는 for문을 만들고 그안에
for문을 사용해 5번 반복시키고 
그안에 if문으로 정답, 오답을 출력하는 코드를 만든다.
for문 밖에다가 continue를 물어보는 코드를 만들고
y를 입력시 다시 for2로 올라가게 만들고
n을 입력시 끝내게 만든다.

break는 멈추기보다는 { }안을 벗어나는 의미

for1을 while(true)로 바꿔도 된다.

728x90

'JAVA' 카테고리의 다른 글

배열, 2차원 배열 정리  (0) 2020.09.12
for 연습05  (0) 2020.09.09
숙제-NumberGame(bufferedReader, while, if )  (0) 2020.09.09
switch 연습02  (0) 2020.09.08
if문 연습04 (가위, 바위, 보 게임)  (0) 2020.09.08
728x90
문제
숫자맞추기 게임
1~100사이의 난수를 발생하여 맞추는 게임

[실행결과]
숫자 입력 : 50
50보다 큽니다

숫자 입력 : 90
90보다 작습니다

...

숫자 입력 : 87
딩동뎅 xx번만에 맞추셨습니다

continue(Y/N) : n
프로그램을 종료합니다

내가한 방법

처음에는 사진처럼 continmue를 만들때 반복문을 전체를 싸지 않고 else안에 생성해서 오류

두번째는 아래 사진처럼 30번줄에 break를 하지않아 반복문을 빠져나오지못해서 33번 문장으로 갈수 없어서 Unreachable code  오류가 나왔다.

그래서 고친 코드는 아래처럼

package loop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NumberGame {
	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int num, user, count = 0;
		String choice;

		System.out.println("숫자맞추기");
		num = (int) (Math.random() * 100) + 1;// 난수생성
		for (;;) {
			while (true) {//
				count++;
				System.out.print("숫자입력 : ");
				user = Integer.parseInt(br.readLine());

				if (user > num) {
					System.out.println(user + "보다 작습니다.");
					System.out.println();
				} else if (user < num) {
					System.out.println(user + "보다 큽니다");
					System.out.println();
				} else {
					System.out.println("딩동댕 " + count + "번만에 맞추셨습니다.");
					break;
				}
			} // while
			System.out.print("continue(Y/N) : ");
			choice = br.readLine();
			if (choice.equals("n")||choice.equals("N"))
				break;
		} // for
		System.out.println("프로그램 종료");
	}
}

선생님 방법

나는 "딩동댕 맞췄습니다"를 while안에 넣었는데 선생님은 while문 밖에다 만들었다.

package loop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NumberGame02 {
	public static void main(String[] args) throws IOException {
		int user, num, count=0;
		String choice, yn;

		
		for(;;) {//무한반복
		 num = (int) (Math.random() * 100) + 1;// 난수생성
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("숫자맞추기");

		while (true) {//
			System.out.print("숫자입력 : ");
			user = Integer.parseInt(br.readLine());
			count++;

			if (user > num) {
				System.out.println(user + "보다 작습니다.");
			} else if (user < num) {
				System.out.println(user + "보다 큽니다");
			} else {
				break;
			}
		}//while문 끝
		
		System.out.println("딩동댕 " + count + "만에 맞추셨습니다.");
		System.out.println("=========");
		
		System.out.println("continue Y/N : ");
		yn = br.readLine();
		if(yn.equals("n")||yn.equals("N")) {
			break; //for문을 나가는거
		}
	}//for
		System.out.println("프로그램 종료");
	}
}

 


a여기에 한술 더해서 continue에 y나 n이 아닌 다른 코드를 넣으면 계속 물어보는 코드를 추가했다.

package loop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NumberTest02_1 {
	public static void main(String[] args) throws IOException {
		int user, num, count = 0;
		String choice, yn;

		for (;;) {// 무한반복
			num = (int) (Math.random() * 100) + 1;// 난수생성
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

			System.out.println("숫자맞추기");

			while (true) {//
				System.out.print("숫자입력 : ");
				user = Integer.parseInt(br.readLine());
				count++;

				if (user > num) {
					System.out.println(user + "보다 작습니다.");
				} else if (user < num) {
					System.out.println(user + "보다 큽니다");
				} else {
					break;
				}
			} // while문 끝

			System.out.println("딩동댕 " + count + "만에 맞추셨습니다.");
			System.out.println("=========");

			while (true) {
				System.out.println("continue Y/N : ");
				yn = br.readLine();
				
				if (yn.equals("n") || yn.equals("N") || yn.equals("y") || yn.equals("Y"))
					break; // for문을 나가는거
				
			} // while
			if (yn.equals("n") || yn.equals("N"))
			break;

		} // for
		System.out.println("프로그램 종료");
	}

}

 

728x90

'JAVA' 카테고리의 다른 글

for 연습05  (0) 2020.09.09
숙제-더하기 연습 프로그램(for, 중첩for, while, bufferedReader,  (0) 2020.09.09
switch 연습02  (0) 2020.09.08
if문 연습04 (가위, 바위, 보 게임)  (0) 2020.09.08
for문 연습03  (0) 2020.09.08

+ Recent posts