java - 如何验证用户输入的字符串? ( java )

标签 java string validation

我已经编辑了这个问题,但在程序的底部我试图编写一个 switch 语句来验证一些代码。我试图让用户输入 Y/N 以继续。如果他们输入 Y,程序应该重新启动。如果他们输入 N,程序应该结束。如果他们输入 Z,他们应该会收到一条错误消息,并再次提示继续是/否? 现在,如果我随机输入一个字母,我会被送回数据输入部分,我不确定为什么。

我还注意到我的计算不对。我假设这与我没有使用 bigdecimal 类这一事实有关。目前,如果我输入 5.6 作为百分比,它会自动假定它是 560%

我是 Java 的新手,不幸的是在挣扎。昨晚有人很友好地帮助了我,但没有公然给我答案,我很感激,因为这让我自己解决了问题。

非常感谢任何帮助,因为我在这门课上遇到了困难。

import java.util.Scanner;
import java.text.NumberFormat;

public class LoanCalculator
{
    public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max) //validate double
    {
        double d = 0;
        boolean isValid = false;
        while(isValid == false)
        {
            System.out.println(prompt); //print prompt for double
            if (sc.hasNextDouble())
            {
                d = sc.nextDouble();

                if (d <= min) //if input <= minimum double
                {
                    System.out.println("Error! Number must be greater than " + min);
                    System.out.println();//print error grater than min double
                }
                else if (d >= max) // if input >= maximum double value 
                {
                    System.out.println("Error number must be less than " + max);
                    System.out.println();//print error less than max double value
                }
                else
                    isValid = true; //else double is valid
            }
            else
            {
                System.out.println("Error! Invalid decimal value.");
                System.out.println();
                sc.nextLine();
            }
        }

        return d; //return double
    }
    //validate integer
    public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
    {
        int i = 0;
        boolean isValid = false;
        while(isValid == false)
        {
            System.out.println(prompt); //print prompt for integer
            if (sc.hasNextInt())
            {
                i = sc.nextInt();

                if (i <= min) //if input <= minimum integer
                {
                    System.out.println("Error! Number must be greater than " + min);
                    System.out.println();//print error grater than min integer
                }
                else if (i >= max) // if input >= maximum integer value
                {
                    System.out.println("Error number must be less than " + max);
                    System.out.println();//print error less than max integer value
                }
                else
                    isValid = true; //else integer is valid
            }
            else
            {
                System.out.println("Error! Invalid integer value.");
                System.out.println();
                sc.nextLine();
            }
        }

        return i; //return integer
    }

    public static void main(String[] args)
    {
        System.out.println("Welcome to the loan calculator"); //welcome user to loan calculator
        Scanner sc = new Scanner(System.in); // create new scanner
        String choice = "y"; //start choice loop
        while (choice.equalsIgnoreCase("y"))
        {
            System.out.println();
            System.out.println("DATA ENTRY");
            double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0); //get user input for loanAmount
            //get user input for interestRate
            double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
            //get user input for years
            int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
            int months = years * 12; // calculate years to months
            //calculate monthly payment
            double monthlyPayment = loanAmount * interestRate/ (1 - 1 / Math.pow(1 + interestRate, months));
            //import currency instance
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            // import percent instance
            NumberFormat percent = NumberFormat.getPercentInstance();
            percent.setMinimumFractionDigits(1); //set fraction digits for percent
            System.out.println("RESULST"); //print results
            //print loanAmount
            System.out.println("Loan Amount: " + currency.format(loanAmount));
            //print interestRate
            System.out.println("Yearly interest rate: " + percent.format(interestRate));
            System.out.println("Number of years: " + years); //print years
            //print monthlyPayment
            System.out.println("Monthly payment: " + currency.format(monthlyPayment));

            boolean quit = false;
            do {
                System.out.println();
                System.out.println("Continue? (y/n): "); //prompt user to continue
                String userinput1 = sc.next();

                char choice1 = userinput1.toLowerCase().charAt(0); 
                switch (choice1) {
                    case 'y':
                        break;
                    case 'n':
                        // case n, do something here
                        quit = true;
                        break;
                    case ' ':
                        System.out.println("Error! This entry is required. Try again.");
                        break;
                    default:
                        System.out.println("Error! Entry must be 'y or 'n''");
                        break;
                }
            } while (!quit);
        }
    }
}

最佳答案

像这样使用开关:

boolean quit = false;
do{ // change your while by this

    // your own stuff here


    // then after all your program stuff
    boolean choiceIsOK = false;
    do{
    String userinput = sc.next();
    char choice = userinput.toLowerCase().charAt(0);
    switch(choice){
    case 'y':
        // case y, do nothing, you could even remove that case.
        choiceIsOK = true;
        break;
    case 'n':
        // case n, do something here
        choiceIsOK = false;
        quit = true;
        break;
    default:
        // error or warning
        System.out.println("Type Y or N to respectively continue or quit");
        break;
    }
    }while(!choiceIsOK);
}while (!quit);

在您的代码中,它将如下所示:

public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator"); //welcome user to loan calculator
Scanner sc = new Scanner(System.in); // create new scanner
//String choice = "y"; //start choice loop [no need for that line anymore]
boolean quit = false; 
do{
        System.out.println();
        System.out.println("DATA ENTRY");
        double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 
                0.0, 1000000.0); //get user input for loanAmount
        //get user input for interestRate
        double interestRate = getDoubleWithinRange(sc, 
                "Enter yearly interest rate: ", 0, 20); 
        //get user input for years
        int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100); 
        int months = years * 12; // calculate years to months
        //calculate monthly payment
        double monthlyPayment = loanAmount * interestRate/
                (1 - 1/Math.pow(1 + interestRate, months)); 
        //import currency instance
        NumberFormat currency = NumberFormat.getCurrencyInstance(); 
        // import percent instance
        NumberFormat percent = NumberFormat.getPercentInstance(); 
        percent.setMinimumFractionDigits(1); //set fraction digits for percent 
        System.out.println("RESULST"); //print results 
        //print loanAmount
        System.out.println("Loan Amount: " + currency.format(loanAmount)); 
        //print interestRate
        System.out.println("Yearly interest rate: " + percent.format(interestRate)); 
        System.out.println("Number of years: " + years); //print years
         //print monthlyPayment
        System.out.println("Monthly payment: " + currency.format(monthlyPayment)); 


        // then after all your program stuff
        boolean choiceIsOK = false;
            do{

                System.out.println();
                System.out.println("Continue? (y/n): "); //prompt user to continue 
                String userinput1 = sc.next();
                    char choice1 = userinput1.toLowerCase().charAt(0);
                    switch(choice1){
                    case 'y':
                        // case y, do nothing, you could even remove that case.
                        choiceIsOK = true;
                        break;
                    case 'n':
                        // case n, do something here
                        choiceIsOK = true; // I fixed this
                        quit = true;
                        break;
                    default:
                        // error or warning
                        System.out.println("Type Y or N to respectively continue or quit");
                        break;
                    }
                }while(!choiceIsOK);

    }while(!quit);

    }           
}

关于java - 如何验证用户输入的字符串? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425099/

相关文章:

java - Eclipse - 如何知道 'real' Java 版本的 Web 应用程序?

java - 为什么没有将操作结果放在并发 HashMap 上? putIfAbsent 的用例是什么?

Java 图形不显示

javascript - 字母数字值的正则表达式,而不是两个连续的下划线下划线

javascript - 如何在 AngularJS 1.2 中仅使用模式的电子邮件验证?

ReactJS 和 Typescript : refers to a value, 但在此处用作类型 (TS2749)

java - 单独的类来播放声音

python - 获取列表中第一个字符串的第一个字符?

python - 如果它们在 Python 中不为空,则连接多个字符串

java - 替换字符串中第 i 次出现的最快方法