如何在Java中限制用户输入

时间:2015-10-10 06:19:21

标签: java input

投资额必须是正数,可以是任何价值。 投资期限为几年,因此应该是积极的。 年利率可在0.25%至14%之间。

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 :(得分: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();
}

答案 1 :(得分:0)

你在说这个:

{{1}}

答案 2 :(得分:0)

好的,你可以使用这样的while循环:

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