简体   繁体   English

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

[英]How to validate a string that the user entered? (Java)

I have edited this question but at the bottom of the program I have tried to code a switch statement to validate some code. 我编辑了这个问题,但在程序的底部,我试图编写一个switch语句来验证一些代码。 I'm trying to ask the user to enter Y/N to continue. 我正在尝试让用户输入Y / N继续。 If they enter Y the program should restart. 如果他们输入Y,程序应重新启动。 If they enter N the program should end. 如果他们进入N,程序应该结束。 If they enter Z they should get an error message and be prompted again with the continue y/n? 如果他们输入Z,他们应该得到一条错误信息并再次提示继续y / n? Right now if I typed a random letter I get sent back to the data entry section and I'm not sure why. 现在,如果我输入一个随机字母,我会被送回数据输入部分,我不知道为什么。

Also I noticed my calculations are off. 我还注意到我的计算结束了。 I'm assuming it has something to do with the fact I'm not using the bigdecimal class. 我假设它与我不使用bigdecimal类的事实有关。 Currently if I typed 5.6 for the percent it automatically assumes it's 560% 目前,如果我输入5.6%的百分比,它自动假定为560%

I'm new to Java and unfortunately struggling. 我是Java的新手,不幸的是苦苦挣扎。 Someone was kind enough to help me last night without blatantly giving me the answers which I appreciated because it made me hash things out on my own. 昨晚有人非常友好地帮助我而没有公然地给我答案我赞赏,因为它让我自己解决了问题。

Any help is definately appreciated since I'm having a hard time with this class. 任何帮助都是绝对值得赞赏的,因为我在这堂课上遇到了困难。

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);
        }
    }
}

Use a switch like this: 使用这样的switch

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);

In your code, it will look like this: 在您的代码中,它将如下所示:

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);

    }           
}

Use if statement, 使用if语句,

choice =sc.next().toLowerCase();
if(choice.equals("y"))
 {
  //
 }
else
if(choice.equals("n"))
 {
  //
 }
else
{
 //invalid input
}

You have to use a conditional, these have the form 你必须使用条件,这些有形式

if(someBooleanCondition){
  doSomething();
}
else{
  doSomethingElse();
}

In your case you would use String.equals() function as your boolean condition. 在您的情况下,您将使用String.equals()函数作为布尔条件。 NOT == as this can give weird results with strings. NOT ==因为这会给字符串带来奇怪的结果。 So you should be doing something like this. 所以你应该做这样的事情。

String userInput = sc.next().toLowerCase();
if(userInput.equals("y")){
 //Its yes, do something here
}
else if(userInput.equals("n")){
 //It's no, do something else
}
else{
  //Handle an invalid entry here
}

A way to have this loop so its will check the input repeatedly is: 有这个循环的方法,所以它将重复检查输入是:

while(true)
String userInput = sc.next().toLowerCase();
if(userInput.equals("y")){
 //Its yes, do something here
break;
}
else if(userInput.equals("n")){
 //It's no, do something else
 break;
}
else{
  //Handle an invalid entry here
}

This will force the user to keep entering stuff until they enter Y or N, if you wish to have them be able to enter a newline character to exit or such you can add that to your loop. 这将强制用户继续输入内容,直到他们输入Y或N,如果您希望他们能够输入换行符退出或者您可以将其添加到循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM