- Change the amount of money into the following format
- 123456 -> \123,456
- 123 -> \123
- 12345678 -> \12,345,678
- String 타입 사용하지 말고 정수타입 사용할 것.
2. 분석
- 정수타입 - %, / 연산 사용
3. 디자인
- 3자리씩 추출하여 배열에 저장 하기 - % 1000 /1000
- 출력부분은 for문과 + 연산을 통해 구현
4. 프로그램 작성
import java.util.Scanner;
public class Homework2Changetheamountofmoney {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of money: ");
long money = input.nextInt();
long[] particle = new long[20]; long part = 0;
int count=1;
part = (long) (money % Math.pow(10,3));
particle[1]=part;
while(part!=0){
money=(long) (money/Math.pow(10,3));
part = (long) (money % Math.pow(10,3));
particle[count+1]=part;
count = count+1;
}
String dollar="$", result="", comma=",";
result=result+particle[1];
for(int i=2;i < count;i++){
result=particle[i]+comma+result;
}
result=dollar+result;
System.out.println(result);
}
}
5. 생각해보기- for(int i=2;i<count;i++) 이 코드부분이 HTML의 형식과 맡지 않는다고 하며 형식이 깨지고 </count> 엘리먼트가 생성된다. 다음에 더 알아보고 포스팅 해볼것.
- 함수화 시켜보자.
- long[] 메모리를 더 효율적으로 관리할 방법은 무엇일까?
- 어떻게 하면 더 좋은 코드를 만들 수 있을까?
댓글 없음:
댓글 쓰기