检测空输入(JAVA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37800423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:49:20  来源:igfitidea点击:

Detecting empty input (JAVA)

javajava.util.scanner

提问by Jane Doe2

So my program has to count the amount of change a person enters in the scanner method, however, two errors must pop out if a) the input is not a number and b) if the input is lacking. I am having a lot of trouble with the latter.

所以我的程序必须计算一个人在扫描仪方法中输入的变化量,但是,如果 a) 输入不是数字,b) 如果缺少输入,则必须弹出两个错误。我对后者有很多麻烦。

import java.util.InputMismatchException;
import java.util.Scanner;
public class MakingChange 
{
public static void main(String[] args)
{

    Scanner input = new Scanner(System.in);  // Reading from System.in
    System.out.print("How much money do you have: ");

    double amountInDollars = 0;

        try {
                amountInDollars = input.nextDouble();
        } catch (InputMismatchException e) {
                System.out.println("INVALID"); //print invalid
        return;
        }

        if (input.equals(" ")){
            System.out.println("INVALID");
            return;
        }


        int amountInPennies = (int) Math.round(amountInDollars * 100);
        amountInPennies = (int) (Math.round(amountInPennies / 5.0)  * 5);

        //toonies
        int numberofToonies = (int)(amountInPennies / 200.00);
        amountInPennies = amountInPennies % 200;
        //loonies   
        int numberofLoonies = (int) (amountInPennies / 100.00);
        amountInPennies = amountInPennies % 100;
        //quarters
        int numberofQuarters = (int)(amountInPennies / 25.00);
        amountInPennies = amountInPennies % 25;
        //dimes      
        int numberofDimes = (int)(amountInPennies / 10.00);
        amountInPennies = amountInPennies % 10;
        //nickels  
        int numberofNickels = (int)(amountInPennies / 5.00);

System.out.println("toonies:" + numberofToonies + ";" + " loonies:" + numberofLoonies + ";" + " quarters:" + numberofQuarters + ";" + " dimes:" + numberofDimes + ";" + " nickels:" + numberofNickels); 

}   
}

So the expected should be "INVALID" but currently, all that returns is a blank space. Thanks!

所以预期应该是“无效”,但目前,返回的只是一个空格。谢谢!

回答by CrazyJavaLearner

Check below code, I have added comments.

检查下面的代码,我已经添加了注释。

import java.util.Scanner;

public class MakingChange {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in); // Reading from System.in
        System.out.print("How much money do you have: ");

        double amountInDollars = 0;
        String amountInString = input.nextLine();
        boolean isValidNum = false;

        if (amountInString.equals("") || amountInString.equals(" ")) { // Empty string check
            System.out.println("Empty String");
        } else if (amountInString.matches("-?\d+(\.\d+)?")) { // valid double check
            amountInDollars = Double.parseDouble(amountInString);
            isValidNum = true;
        } else {
            System.out.println("Number Format error");
        }

        if (isValidNum) {
            int amountInPennies = (int) Math.round(amountInDollars * 100);
            amountInPennies = (int) (Math.round(amountInPennies / 5.0) * 5);

            // toonies
            int numberofToonies = (int) (amountInPennies / 200.00);
            amountInPennies = amountInPennies % 200;
            // loonies
            int numberofLoonies = (int) (amountInPennies / 100.00);
            amountInPennies = amountInPennies % 100;
            // quarters
            int numberofQuarters = (int) (amountInPennies / 25.00);
            amountInPennies = amountInPennies % 25;
            // dimes
            int numberofDimes = (int) (amountInPennies / 10.00);
            amountInPennies = amountInPennies % 10;
            // nickels
            int numberofNickels = (int) (amountInPennies / 5.00);

            System.out.println("toonies:" + numberofToonies + ";" + " loonies:"
                    + numberofLoonies + ";" + " quarters:" + numberofQuarters
                    + ";" + " dimes:" + numberofDimes + ";" + " nickels:"
                    + numberofNickels);
        }

    }
}

回答by Seek Addo

try this and should work fine for you.

试试这个,应该适合你。

Scanner input = new Scanner(System.in);  // Reading from System.in
    System.out.print("How much money do you have: ");

    double amountInDollars = 0;
    String emp = input.nextLine();

    try {

        // if the user doesn't enter anything and press enter or entered value is empty
        if (emp.isEmpty() || emp.equals(" ")) { 
            System.out.println("Invalid input");
            return;
        }

    }catch (InputMismatchException e){
       //catch the message
        e.printStackTrace();
    }
    // if string entered is not double
    boolean isnum = emp.chars().allMatch(Character::isAlphabetic);

    if (!isnum) { // if is a Number then we pass it in
        amountInDollars = Double.parseDouble(emp);
    } else {
       // we pass exception message to catch
        System.out.println("Invalid Input: Double values only please");
        return;
    }

    if (amountInDollars < 0) { // if the value is 'Negative'
        System.out.println("INVALID");
        return;
    }


    int amountInPennies = (int) Math.round(amountInDollars * 100);
    amountInPennies = (int) (Math.round(amountInPennies / 5.0)  * 5);

    //toonies
    int numberofToonies = (int)(amountInPennies / 200.00);
    amountInPennies = amountInPennies % 200;
    //loonies
    int numberofLoonies = (int) (amountInPennies / 100.00);
    amountInPennies = amountInPennies % 100;
    //quarters
    int numberofQuarters = (int)(amountInPennies / 25.00);
    amountInPennies = amountInPennies % 25;
    //dimes
    int numberofDimes = (int)(amountInPennies / 10.00);
    amountInPennies = amountInPennies % 10;
    //nickels
    int numberofNickels = (int)(amountInPennies / 5.00);

    System.out.println("toonies:" + numberofToonies + ";" + " loonies:" + numberofLoonies + ";" + " quarters:" + numberofQuarters + ";" + " dimes:" + numberofDimes + ";" + " nickels:" + numberofNickels);

Let me know if it works out.

让我知道它是否有效。

回答by Silverclaw

As far as I see, you are testing whether your scanner object equals a string literal, which makes no sense at all. First, get a string, using any of the scanner's nextXXX-methods. Then, check if that string is empty, by using someString.equals(""), or even better in my opinion, someString.isEmpty().

据我所知,您正在测试您的扫描仪对象是否等于字符串文字,这完全没有意义。首先,使用任何扫描器的nextXXX-methods获取一个字符串。然后,检查该字符串是否为空,通过使用someString.equals(""),或者在我看来更好,someString.isEmpty().

回答by LowLevel

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    BigDecimal money = getBigDecimal(sc); // When using scanner as parameter your performance increases because you don't create new scanners every time if you use the scanner for different purposes or within a recursive function.
    System.out.printf("You have %(,.2f dollars%n", money); // Just an example of your output.
}

public static BigDecimal getBigDecimal(Scanner sc) {
    System.out.print("How much money do you have? ");
    if (sc.hasNextBigDecimal()) { // if a BigDecimal value is typed
        return sc.nextBigDecimal();
    }
    sc.next(); // else ignore input
    System.out.println("Please, type amount.");
    return getBigDecimal(sc); // recursion
}

For money you better use BigDecimal(believe me, or don't believe me). Further you can use BigDecimalfunctions to make your calculations.

为了钱,你最好使用BigDecimal(相信我,或者不相信我)。此外,您可以使用BigDecimal函数进行计算。

https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.htmlhttp://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorialhttp://www.tutorialspoint.com/java/math/java_math_bigdecimal.htm

https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial http://www. tutorialspoint.com/java/math/java_math_bigdecimal.htm