投資金額必須是積極的,可以是任意值。 投資期限是幾年,所以應該是積極的。 年利率可能介於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);
}
}
}
我已經做了基本的程序,但是,我不知道如何添加限制。
確定..什麼'如果'聲明? –
參見:如何篩選掃描儀輸入(http://stackoverflow.com/questions/20834913/filtering-java-util-scanner-input) – agold