2014-11-02 6 views
-1

사용자 입력 값을 기반으로 for 루프를 사용하여 월간 복리 계산을 계산하는 프로그램을 작성해야했습니다. 하지만 몇 가지 문제가 있습니다. 1000 5 54개월Java 월간 복리이자

원금, 이자율, 기간 >>
Month: Interest: Principal: 
    1 $4.17  $1004.17 
    2 $4.18  $1008.35 
    etc. etc.  etc. 

내 문제는 문자열 입력 유효성 검사입니다 :

입력하세요 다음

예 입력 및 출력처럼 보일 것입니다. 사용자가 몇 달 또는 몇 년을 입력하지 않으면 사용자에게 알리고 다시 입력 할 수 있도록 재촉해야합니다. 그러나 현재 코드에서는 사용자가 몇 개월 또는 몇 년을 입력했다고해도 계속 입력해야합니다.

public Calculator() { 
    Scanner input = new Scanner(System.in); 
    boolean error = false; 

    while (!error) { 
     System.out 
       .print("Please input the following: principal, interest rate, term >> "); 
     double principal = input.nextDouble(); 
     double interest_rate = input.nextDouble(); 
     int term = input.nextInt(); 
     String MonthOrYear = input.nextLine(); 
     double amount = 0; 

     if (interest_rate <= 0 || term <= 0 || principal <= 0) { 
      System.out 
        .println("The term, interest rate and principal must be greater than zero"); 
      continue; 
     } 
     if (!MonthOrYear.equals("month") || (!MonthOrYear.equals("year"))) { 
      System.out.println("Please input either month or year"); 
      continue; 
     } 

     System.out.println("Month: " + " Interest: " + "Principal: "); 

     for (int month = 1; month <= term; month++) { 
      double interest = principal * interest_rate/100; 
      principal = principal + interest; 
      System.out.printf("%4d %10.2f %10.2f\n", month, interest, 
        principal); 

     } 
     break; 
    } 
} 
+2

이 조건이 항상 true 인 경우 (MonthOrYear.equals는 ("달") || (MonthOrYear.equals는 ("년"))!!) , MonthOrYear의 값에 관계없이 && 및 ||이 아니어야합니다. – Michael

+1

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Deltharis

답변

0

nextInt와 nextLine을 사용할 때 흔히 저지르는 실수입니다.

String MonthOrYear = input.nextLine(); 

로 : 당신의 라인을 변경

String MonthOrYear = input.next();