Menu
Coddy logo textTech

String Formatting

Coddy Java 여정의 기초 섹션에 포함된 레슨 — 73개 중 69번째.

Java에서 String.format()은 형식화된 문자열을 생성하는 데 사용되는 강력한 메서드입니다. 이 메서드를 사용하면 읽기 쉽고 사용자 정의 가능한 방식으로 텍스트와 변수를 결합할 수 있습니다. 이 메서드는 형식 지정자를 사용하여 변수가 문자열에 삽입되는 방식을 정의합니다.

String.format()의 기본 구문은 다음과 같습니다:

String formattedString = String.format("format_string", arg1, arg2, ...);
  • format_string: 텍스트와 형식 지정자를 포함하는 문자열입니다.
  • arg1, arg2, ...: format_string에 삽입될 변수들입니다.

다음은 몇 가지 일반적인 형식 지정자입니다:

  • %s: 문자열을 삽입합니다.
  • %d: 10진수(정수)를 삽입합니다.
  • %f: 부동 소수점 숫자를 삽입합니다.
  • %b: 불리언 값을 삽입합니다.
  • %c: 문자를 삽입합니다.
  • %n: 줄바꿈 문자를 삽입합니다.

서식을 더 자세히 제어할 수도 있습니다:

  • %.2f: 부동 소수점 숫자를 소수점 둘째 자리까지 형식화합니다.
  • %10s: 10자 너비의 필드 내에서 문자열을 오른쪽으로 정렬하여 삽입합니다.
  • %-10s: 문자열을 삽입하며, 10자 너비의 필드 내에서 왼쪽으로 정렬합니다.
  • %03d: 정수를 삽입하며, 3자리 너비가 되도록 앞을 0으로 채웁니다.

예제는 다음과 같습니다:

String name = "Alice";
int age = 30;
double price = 19.99;

String formatted = String.format("Name: %s, Age: %d, Price: %.2f", name, age, price);
System.out.println(formatted);
// 출력: Name: Alice, Age: 30, Price: 19.99

이 예제에서 %sname으로, %dage로, 그리고 %.2f는 소수점 둘째 자리까지 형식화된 price로 대체됩니다.

challenge icon

챌린지

쉬움

다음 인자들을 받는 createFormattedString이라는 이름의 메서드를 생성하세요:

  1. 문자열 productName.
  2. 정수 quantity.
  3. 실수(double) unitPrice.

메서드는 다음 형식으로 이 값들을 결합한 포맷된 문자열을 반환해야 합니다:

Product: [productName], Quantity: [quantity], Unit Price: [unitPrice]

unitPrice는 소수점 다섯째 자리까지, quantity는 소수점 첫째 자리까지 포맷하세요 (double로 변환하세요).

예를 들어, productName이 "laptop"이고, quantity가 3이며, unitPrice가 1299.9999인 경우, 메서드는 다음을 반환해야 합니다:

Product: laptop, Quantity: 3.0, Unit Price: 1299.99990

직접 해보기

import java.util.Scanner;

public class Main {
    public static String createFormattedString(String productName, int quantity, double unitPrice) {
        // 여기에 코드를 작성하세요
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String product = scanner.nextLine();
        int qty = scanner.nextInt();
        double price = scanner.nextDouble();
        String formattedString = createFormattedString(product, qty, price);
        System.out.println(formattedString);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

기초의 모든 레슨