2015-10-10 216 views
-1

投資金額必須是積極的,可以是任意值。 投資期限是幾年,所以應該是積極的。 年利率可能介於0.25%至14%之間。如何限制用戶輸入在Java

import java.util.Scanner; 

public class InterestCalculator{ 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 

     Scanner input = new Scanner(System.in); 

     // Entering the interest rate 
     System.out.print("Please Enter the annual interest rate between 0.25 to 10 : "); 
     double annualInterestRate = input.nextDouble(); 

     double monthlyInterestRate = annualInterestRate/1200; 

     System.out.print("Enter number of years: "); 
     int numberOfYears = input.nextInt(); 

     // Entering the amount earned 
     System.out.print("Enter Amount: "); 
     double Amountofinterest = input.nextDouble(); 

     // Calculating 
     double moneyearned = Amountofinterest * monthlyInterestRate; 

     // Displaying the results 
     System.out.println("The money earned is $" + 
     (int) (moneyearned * 100)/100.0); 
     int i; 

     for (i = 1; i <= numberOfYears * 12; i++) { 
      double Balance = Amountofinterest + moneyearned; 
      Amountofinterest = Balance; 
      monthlyInterestRate = moneyearned + 0.01; 
      System.out.println(i + "\t\t" + Amountofinterest 
        + "\t\t" + monthlyInterestRate + "\t\t" + Balance); 

     } 

    } 
} 

我已經做了基本的程序,但是,我不知道如何添加限制。

+3

確定..什麼'如果'聲明? –

+0

參見:如何篩選掃描儀輸入(http://stackoverflow.com/questions/20834913/filtering-java-util-scanner-input) – agold

回答

0

您可以使用循環反覆要求輸入直到它是有效的:

double annualInterestRate = 0; 
while (annualInterestRate < 0.25 || annualInterestRate > 10){ 
    System.out.print("Please Enter the annual interest rate between 0.25 to 10 : "); 
    annualInterestRate = input.nextDouble(); 
    if (annualInterestRate < 0.25 || annualInterestRate > 10){ 
     System.out.println("Please enter a value between 0.25 and 10"); 
    } 
} 
//if you reach this point, input is valid because it is neither <0.25 or >10 

您可以爲需要滿足一定的條件的所有值做到這一點。只要確保你初始化變量之前循環,並將其設置爲無效值,否則循環將無法運行。

其他變量:

int numberOfYears = -1; //or 0 is you don't allow 0 years 
while (numberOfYears < 0){ //or <= 0 if you don't allow 0 years 
    System.out.print("Enter number of years: "); 
    numberOfYears = input.nextInt(); 
} 
double Amountofinterest = -1; //or 0 
while (Amountofinterest < 0){ //or <= 0 
    System.out.print("Enter Amount: "); 
    Amountofinterest = input.nextDouble(); 
} 
+0

你在你在定義一個新的'雙annualInterestRate'。你應該刪除'double'。 – agold

+0

好眼睛。我的錯。編輯它 – Arc676

+0

謝謝..這完美的年度限制...可以請告訴我其他2限制...非常感謝您的幫助和快速回復。 –

0

你說的是這個:

while(input.nextDouble()<0){ 
     System.out.println("Please enter positive investment"); 

    } 
0

好了,你可以再使用while循環是這樣的:

int numberOfYears = -1; 
    System.out.print("Enter number of years: "); 
    while(numberOfYears < 0){ 
    numberOfYears = input.nextInt(); 
    }