프로그래밍 이야기/JAVA 공부

자바키값저장 자바변수값저장 자바값입력자바값 출력

글쓰는 개발자 김뉴네 2023. 10. 2. 22:12
728x90
반응형

- 키보드에서 키 하나를 입력하면  프로그램에서는 숫자로된 키코드를 읽을 수 있다.

- 키코드를 읽기 위해서는  System.in의 read()를 이용하면 된다.

 

int keyCode = System.  + in. + read();

 

- 보통 System.in.read()로 읽은 키코드를 대입 연산자(=)를 사용해서 int 변수에 저장하며 변수에 저장된 값을 조사하면 입력된 키가 무엇인지 알수 있다. 

숫자
0 = 48 / 1 = 49 /  2=50  / 3=51 / 4=52 / 5=53 / 6=54 / 7=55 / 8=56 / 9=57
알파벳
A=65 / B=66 / C=67 / D=68 / E=69 / F=70 / G=71 / H=72 / I=73 / J=74 / K=75 / L=76 / M=77 / N=78 
O=79 / P= 80 / Q= 81 /R= 82 /S= 83 / T=84 / U=85 / V=86 / W=87 / X=88 / Y=89 / Z= 90
a= 97 / b= 98 / c= 99 / d=100 / e= 101 / f=102 / g= 103 / h= 104 / i= 105 / j= 106 / k= 107 / l= 108 / m=109 / n=110
o= 111 / p= 112 / q=113 / r= 114 / s= 115 / t= 116 / u= 117 / v = 118 / w = 119 / x = 120 / y = 121 / z = 122
기능키
BACK SPACE = 8 / TAB = 9 / ENTER = [ CR = 13, LF = 10]  / SHIFT = 16 / CONTROL = 17 / ALT = 18
ESC = 27/ SPACE =32/ PAGEUP =33 / PAGEDN = 34
방향키
← =  37 / ↑ = 38 / → = 39 / ↓ = 40

- main() 메서드 끝에 throws exception 이 붙어 있는데 이것은 System.in.read()에 대한 예외처리 코드 이다  예외처리란 예외가 발생했을때 어떻게 처리할 것인가를 말하는 것인데 throws Exception은 단순히 모니터에 예외 내용 출력만한다.

package sec01.exam01;

public class KeyCodeExample {
    public static void main(String[] args) throws Exception{
        int keyCode;

        keyCode = System.in.read();
        System.out.println("keyCode:"+keyCode);

        keyCode = System.in.read();
        System.out.println("keyCode:"+keyCode);

        keyCode = System.in.read();
        System.out.println("keyCode:"+keyCode);

    }
}

package sec01.exam01;

public class QStopExample {
    public static void main(String[] args) throws  Exception{
        int keyCode;

        while(true){
            keyCode = System.in.read();
            System.out.println("keyCode:"+keyCode);
            if(keyCode ==113){
                break;
            }
        }
        System.out.println("종료");
    }
}

- System.in.read() 단점은 키코드를 하나씩 읽기 때문에 2개 이상의 키가 조합된 한글을 읽을 수 없다는 것이다 그리고 키보드로 부터 입력된 내용을 통 문자열로 읽지 못하기 때문에 이러한 단점을 보완하기 위해 Scanner 클래스를 제공하고 있다.

 

- Scanner scanner = new Scanner (System.in)

- String inputData = scanner.nextLine();

 

package sec01.exam01;

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) throws  Exception{
        Scanner scanner = new Scanner(System.in);
        String inputData;

        while(true){
            inputData = scanner.nextLine();
            System.out.println("입력된 문자열:\""+inputData+"\"");
            if(inputData.equals("q")){
                break;
            }
        }

        System.out.println("종료");
    }
}
728x90
반응형