[Java] 자바 #4 콘솔 입출력 해보기

자바 입출력


콘솔 출력

1. print 메소드 : 개행이 없음. 

2. println 메소드 : 개행이 이루어짐 - print line 의 약자임

3. printf 메소드(***) : 미리 정해진 **형식 문자**를 통해서 내용을 출력 - print format의 약자임


형식문자

a. %s : String의 약자

b. %d : Decimal -> 정수(byte, short, int, long)

c. %f : Float -> 실수(float, double)

d. %c : Char 

e. %b : Boolean


System.out.print("하나");

System.out.print(100);

System.out.print(true);

System.out.print('A');


- 요구사항 : 홍길동에게 인사하세요.

String name = "홍길동";

System.out.println("안녕하세요."+name+"님");

System.out.printf("안녕하세요.%s님\n",name);


//요구사항 : 안녕하세요. 홍길동님. 잘가세요. 홍길동님.

System.out.println("안녕하세요."+name+"님. 잘가세요." +name+"님");

System.out.printf("안녕하세요. %s님. 잘가세요. %s님.\n",name,name);


//성적 출력.

String name1 = "홍길동";

int kor1 = 100;

int eng1 =90;

int math1 =80;



String name2 = "아무개";

int kor2 = 10;

int eng2 =9;

int math2 =8;


System.out.println("===========================================");

System.out.println("[이름]\t[국어]\t[영어]\t[수학]\t[평균]");

System.out.println("===========================================");


System.out.println(name1+"\t"+kor1+"\t"+eng1+"\t"+math1+"\t"+((kor1+eng1+math1)/3.0));

System.out.printf("%s\t%d\t%d\t%d\t%4.2f\n",name2,kor2,eng2,math2,(kor2+eng2+math2)/3.0);

Oracle + JDBC -> SQL(insert문 할때)!

- insert into tblBoard(seq, id, title, date, count) values(10,'hong','게시판입니다.',2018-07-05',100);

int seq = 10;

String id = "hong";

String title = "게시판입니다.";

String date = "2018-07-05";

int count =  100;

- 이렇게 출력해서 더미데이터를 만들 수 있다.

System.out.println("insert into tblBoard(seq, id, title, date, count) values("+seq+",'"+id+"','"+title+"','"+date+"',"+count+")");

System.out.printf("insert into tblBoard(seq, id, title, date, count) values(%d,'%s','%s','%s',%d)\n",seq,id,title,date,count);


형식문자 추가기능

1.%(숫자)s : 숫자만큼의 문자수 너비로 확보 + 출력(고정 너비 출력)

양수 : 우측정렬  음수 : 좌측정렬

%s %d %f (%c %b) 에도 사용 가능!

String txt1="abc";

System.out.printf("[%s]\n",txt1); -> [abc]




System.out.printf("[%10s]\n",txt1); -> [       abc]

System.out.println("1234567890");   -> 1234567890

System.out.printf("[%-10s]\n",txt1);-> [abc       ]


System.out.printf("가격 : %5d원\n",1000); -> 가격 :  1000원



가격 : 10000000원

System.out.printf("가격 : %5d원\n",500);   -> [가격 :   500원]

System.out.printf("가격 : %5d원\n",12000); -> [가격 : 12000원]

System.out.printf("가격 : %5d원\n",100);   -> [가격 :   100원]

System.out.printf("가격 : %5d원\n",550);   ->  [가격 :   550원]

System.out.printf("가격 : %5d원\n",10000000); -> 숫자가 너무 커져서 %5d의 의미가 없어짐 -> 그래서 가장 큰 숫자에 맞게 설정.

2. %( .숫자)f

실수형만 사용 가능. 

소수이하 몇자리까지 출력?


double m = 1234.567890123456;

System.out.println("실수 : "+m); -> [실수 : 1234.567890123456]

System.out.printf("실수 : %.3f\n",m); -> [실수 : 1234.568]


m=10;

System.out.println("실수 : "+m); -> [실수 : 10.0]

System.out.printf("실수 : %.0f\n",m); -> [실수 : 10]


3. %d

숫자형(%d, %f)만 사용가능.

자릿수 표현(천단위 표기)

System.out.printf("가격 : %d원\n",10000000); -> [가격 : 10000000원]

System.out.printf("가격 : %,d원\n",10000000); -> [가격 : 10,000,000원]



위의 3가지를 모두 합쳐서...

double price1 = 12.5, price2 =1200, price3 = 500.3;

System.out.printf("price : $%,4.1f\n",price1); -> [price : $12.5]

System.out.printf("price : $%,6.1f\n",price2); -> [price : $1,200.0]

System.out.printf("price : $%,5.1f\n",price3); -> [price : $500.3]



------------------------------------------------입력------------------------------------------------

콘솔 입력

-사전작업 : 1. 메인메소드옆에 throws Exception 기재


1. System.in.read() 메소드

 -바이트단위의 입력도구

2. BufferedReader 클래스

 -문자단위의 입력도구(2Bytes단위)

3. Scanner 클래스

 -문자단위의 입력도구(2Bytes단위)

요구사항 : 사용자에게 문자를 1개입력받아서 화면에 그대로 출력.

사용자로부터 문자 입력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Class{
    public static void main(String[] args) throws Exception{
 
        int a = System.in.read();
        System.out.println(a);
        System.out.println((char)a);
        //cSystem.out.printf("%c\n",a);
        
        a = System.in.read();
        System.out.println(a); //입력된 값 출력
        
        a = System.in.read();
        System.out.println(a);
        
        a = System.in.read();
        System.out.println(a);
        
        a = System.in.read();
        System.out.println(a);
        System.out.println("끝");
    }
}
 
cs


BufferedReader 사용 예제 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//클래스 임포트
//import 패키지.Class명
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class Class{
    public static void main(String[] args) throws Exception{
 
        //사전작업
        //1. throws Exception
        //2. 클래스 임포트, Class Import
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 
        System.out.println("문자를 입력하세요."); // Label 
        
        //reader 는 입력도구랍니다.
        String txt = reader.readLine();// == System.in.read()와 같은기능 
        System.out.println(txt);
        txt = reader.readLine(); 
        System.out.println(txt);
        
        //이름을 입력하면 인사를 해주는 프로그램..
 
        System.out.println("이름을 입력해주세요.");
        txt = reader.readLine();
        System.out.printf("%s님 안녕하세요\n",txt);
 
 
 
 
        //요구사항. : 태어난 년도를 입력하여 그 사람의 나이를 구하는 프로그램!(전제조건 : 현재가 무조건 2018년이라고 가정)
        System.out.println("생년을 입력하시오");
        String data = reader.readLine();
        //Short.parseShort("100");
        //Byte.parseByte("100");
        //Long.parseLong("100");
        //Float.parseFloat("3.14");
        //Double.parseDouble("3.14");
        //Boolean.parseBoolean("true");
 
        //문자형(숫자) -> 숫자형(숫자) 로 변환작업 해야함
        int year = Integer.parseInt(data);
        //System.out.println(2018-year);
        if(year > 2018){
        }
        else{
            System.out.printf("태어난 년도가 %d년도이면 %d세 입니다.\n",year,2018-year);
        }
 
        //BufferedReader사용, 입력, "문자열" -> 그대로 ->"문자열"
        // 입력은 문자열이지만 숫자가 필요하면 -> Integer.parseInt()를 통해서 변환 후 int 변수에 저장!
 
        String data2 = reader.readLine(); //"a" <- 얘는 문자열 하지만 나는 'a'가 필요하다면
        char c = data2.charAt(0);
    }
}
 
cs


댓글

Designed by JB FACTORY