회사 손코딩문제이다. 처음 봤을 땐 간단해보였지만 아직 부족해서 잘 몰랐다. 다시 공부해야할 것 같아 블로그를 써본다.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("가격을 입력하세요: ");
int price = scanner.nextInt();
DecimalFormat formatter = new DecimalFormat("#,###");
String formattedPrice = formatter.format(price);
System.out.println("입력하신 가격은 " + formattedPrice + "원입니다.");
}
}
외부함수 DecimalFormat을 사용하면 간단하게 입력받은 값에 ,를 추가 할 수 있었다.
String formattedPrice = formatter.format(price);
하지만
Decimalformat 이라는 외부함수를 사용하지 말라고 하니 막막해진 느낌이든다...
import java.util.Scanner;
public class Calculate1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("가격을 입력하세요: ");
int price = scanner.nextInt();
String formattedPrice = ""; // 가격을 변환한 문자열을 저장할 변수를 초기화합니다.
String priceStr = String.valueOf(price); // 입력받은 가격을 문자열로 변환합니다.
int commaCount = (priceStr.length() - 1) / 3; // 천 단위마다 찍어줄 쉼표(,)의 개수를 계산합니다.
for (int i = 0; i < priceStr.length(); i++) {
formattedPrice += priceStr.charAt(i); // 문자열의 각 자릿수를 하나씩 읽어서 formattedPrice 문자열에 추가합니다.
if (i < priceStr.length() - 1 && (priceStr.length() - 1 - i) % 3 == 0) {
formattedPrice += ","; // 천 단위마다 쉼표(,)를 찍어줍니다.
}
}
System.out.println(formattedPrice);
}
}
'코딩테스트 예제' 카테고리의 다른 글
프로그래머스 나이 출력 예제 (0) | 2023.05.12 |
---|---|
프로그래머스 아이스아메리카노 예제 (0) | 2023.05.12 |
프로그래머스 옷가게 할인받기 (0) | 2023.04.16 |
프로그래머스 배열의 평균값 구하기 (0) | 2023.04.16 |
프로그래머스 피자나눠먹기3 (0) | 2023.04.15 |