Java printf / Scanner

hee·2022년 12월 21일
0

println의 단점

1. 실수의 자리수 조절 불가

public class PrintfEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

			System.out.println(10/3);
	}

}
//출력결과 : 3

정수 / 정수 이기 때문에 결과가 정수가 나옴
둘중 하나라도 실수로 바꾸면 실수 결과가 나옴

2. 10진수로만 출력

public class PrintfEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

			System.out.println(0x1A);
	}

}
//출력결과 : 26

printf로 출력형식 지정가능

public class PrintfEx01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

			System.out.printf("%.2f", 10.0/3);
			//실수를 소수점 둘째자리까지 출력 3.33
			System.out.printf("%d", 0x1A);
			//정수10진수 출력 26
			System.out.printf("%x", 0x1A);
			//16진수 출력 1A
	}

}

"%.2f", "%d", "%x" 는 지시자라고 부름

설명
%b불리언 형식 출력
%d10진 정수 출력
%o8진 정수 출력
%x, %X16진 정수 출력
%f부동 소수점 실수 출력
%e, %E지수형식 출력
%c문자 출력
%s문자열 출력

더 많은 지시자는 JavaAPI -> Formater

System.out.printf("age:%d year:%d\n", 14, 2017);
문자열 안에 지시를 같이 사용 가능. 값의 갯수도 지시자의 갯수만큼 적어야 함.

printf는 줄바꿈을 하지 않기때문에 '\n, %n' 개행문자를 작성해야함.
OS마다 개행문자가 다름. '%n'은 OS에 관계 없이 사용.

2진은 없음 그래서 정수를 2진 문자열로 변환해주는 메소드를 사용해야함
System.out.printf("%s", Integer.toBinaryString(15));

8진수와 16진수에는 접두사가 나오지 않지만(8진수 0과 16진수 0x), #을 사용하면 접두사도 출력
System.out.printf("%#o", 15);
System.out.printf("%#x", 15);

실수 출력 지시자 %f - 지수형식 %e, %f와 %e중 간략한 형식으로 출력하는 지시자 %g

			System.out.printf("%d%n", 15); //10
			System.out.printf("%o%n", 15); //8
			System.out.printf("%x%n", 15); //16
			
			System.out.printf("%#o%n", 15); //8
			System.out.printf("%#x%n", 15); //16
			
			System.out.printf("%s", Integer.toBinaryString(15));
			
			//float f = 123.456789f;
			double f = 123.456789;
			System.out.printf("%f%n",f);
			System.out.printf("%e%n",f);
			System.out.printf("%g%n",f);
			// float는 정밀도가 7자리이기 때문에 7자리까지만 정확함
			//double은 15자리까지

지시자에 숫자를 붙이면 출력되는 자릿수를 정할수 있다.

System.out.printf("[%5d]%n", 10); //5 자리 출력
System.out.printf("[%-5d]%n", 10); //왼쪽정렬 -
System.out.printf("[%05d]%n", 10); //공백을 0으로 채움

double d = 1.23456789;
System.out.printf("%14.6f%n", d);

System.out.printf("[%s]%n", "www.codechobo.com");
System.out.printf("[%20s]%n", "www.codechobo.com");
System.out.printf("[%-20s]%n", "www.codechobo.com");
System.out.printf("[%.10s]%n", "www.codechobo.com");

System.out.printf("d=%14.10f%n", d); 전체자리 14자리중 소수점 아래 10자리 출력

%전체자리.소수점아래자리f
빈자리는 소수점 아래는 0, 정수는 공백으로 채움


Scanner class란?

  • 화면으로부터 데이터를 입력받는 기능을 제공하는 클래스
    클래스 : 어떤 기능을 제공하는것 (6장)

사용방법

  1. import 문 추가 (7장)

  2. Scanner 객체의 생성 (6장)
    (printf와 같은 클래스는 객체를 생성하지 않아도 됨,
    ex : Scanner scanner = new Scaner(System.in);)

  3. 생성하는 Scanner 객체를 사용
    int num = scanner.nextInt(); //화면에서 입력받는 정수(int)를 num에 저장

String input = scanner.nextLine();
int num = Integer.parseInt(input);

profile
고군분투 코린이의 코딩일기

0개의 댓글