피보나치 수열이란?

> 처음 두 항을 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

문자열 암호화

조건 

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

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
public class Lotto {
	public static void main(String[] args) {
		boolean swit[] = new boolean[45];
		int lotto[] = new int [6];
		int w, r;

		w = 0;
		while(w < 6) {
			r = (int)(Math.random()*45); // 0 ~ 44
			if(swit[r] == false) {
				swit[r] = true;
				lotto[w] = r+1;	     // 1 ~ 45
				w++; 
			}
		}
		for(int i =0; i < lotto.length; i++) {
			System.out.print(lotto[i]+ " ");
		}
	}
}

로또 번호 생성기

 

 

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

[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 배열 순차 정렬  (0) 2021.05.11
[자바] Baseball Game  (0) 2021.05.10
[자바] 숫자 맞추기 UP&DOWN  (0) 2021.05.10
[자바] 문자열이 숫자인지 판별하기  (0) 2021.05.10
import java.util.Scanner;

public class Baseball {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		
		// 선언부
		int r_num[] = new int[3];
		int u_num[] = new int[3];
		boolean clear;
		
		boolean swit[] = new boolean[10]; // 0 ~ length-1
		//				 allocation(동적할당)
		
		// 초기화
		clear = false;
		for(int i=0; i<swit.length; i++) {
			swit[i] = false;
		}
		int w, r;
		
		w = 0;
		while(w < 3) {
			r = (int)(Math.random()*9);// 0~8
			if(swit[r] == false) {
				swit[r] = true;
				r_num[w] = r + 1;  // 1~9
				w++;
			}
		}
		for(int i=0; i<r_num.length; i++) {
			System.out.print(r_num[i]+ " ");
		}
		System.out.println();
		
		////////////////////////////////  loop
		w = 0;
		
		while(w<10) {
		// user 입력
		while(true) {
			for(int i=0; i<u_num.length; i++) {
				System.out.print((i + 1)+"번째 수 >> ");
				u_num[i] = scn.nextInt();
				}
				if(u_num[0] != u_num[1]
						&& u_num[1] != u_num[2]
								&& u_num[0] != u_num[2]) {
					break;
				}
				System.out.println("같은 숫자를 입력하셨습니다. 다시 입력해 주세요.");
			}
			
			// 비교			-> 탈출
			// 스트라이크, 볼
			int strike, ball;
			strike = 0;
			ball = 0;
			
			// ball
			for(int i=0; i< r_num.length; i++) {	// 0 1 2
				for (int j=0; j<u_num.length; j++) {// 0 1 2
					if(u_num[i] == r_num[j] && i != j) {
						ball++;
					}
				}
			}
			
			// strike
			for(int i=0; i< r_num.length; i++) {
				if(u_num[i] == r_num[i]) {
					strike++;
				}
			}
		// 맞췄을 경우
			if(strike > 2) {
				clear = true;
				break;
			}
		// 메세지 출력
			System.out.println(strike + "스트라이크"+ ball +"볼입니다.");
			w++;
		}
		////////////////////////////////
		// 결과출력
		if(clear) {
			System.out.println("Game Clear!!!");
		}else {
			System.out.println("Game Over~");
		}
	}
}

Baseball Game

 

조건 

> 기회는 10번
> 3개의 숫자는 같은 수이면 안 된다.
> 자리수와 숫자가 같은 경우 : strike
> 숫자만 같은 경우 : ball

 

 

 

 

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

[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 배열 순차 정렬  (0) 2021.05.11
[자바] 로또 번호 생성  (0) 2021.05.10
[자바] 숫자 맞추기 UP&DOWN  (0) 2021.05.10
[자바] 문자열이 숫자인지 판별하기  (0) 2021.05.10
import java.util.Scanner;

public class UpDown {
	public static void main(String[] args) {
		// 1 ~100까지 숫자 찾기 게임! 기회는 단 10회!
		Scanner scn = new Scanner(System.in);
		int temp = 0;
		int count = 0;
		boolean clear = false;
		
		int comNum = (int)(Math.random()*100)+1;	// comNum 1~100까지 랜덤 수 뽑기
		
		while(count<10) {
			System.out.print("user : ");
			int userNum = scn.nextInt();		// userNum 입력

			if(comNum > userNum ) {			// comNum이 userNum보다 클 경우
				temp = 1;			// temp에 1 저장
			}else if (comNum < userNum) {		// comNum이 userNum보다 작을 경우
				temp = 2;			// temp에 2 저장
			} else {				// comNum이 userNum보다 같을 경우
            			clear = true;			// clear에 true를 저장
				break;				// if블럭 빠져 나가기
			}
			
			switch(temp) {							
			case 1 :
				System.out.println("UP!");
				break;
			case 2 :
				System.out.println("DOWN!");
				break;
			}
			count++;
		}
		if(clear == true) {
			System.out.println("Congratulations! Game Clear!!!");
		} else {
			System.out.println("GameOver~~~");
		}
	}
}

Scanner로 숫자를 입력받아서 UP & DOWN 게임

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

[자바] 가위바위보 게임  (0) 2021.05.11
[자바] 배열 순차 정렬  (0) 2021.05.11
[자바] 로또 번호 생성  (0) 2021.05.10
[자바] Baseball Game  (0) 2021.05.10
[자바] 문자열이 숫자인지 판별하기  (0) 2021.05.10

+ Recent posts