0
votes

If ENTER is inputted, i.e. null or empty string, the following error is thrown. Can't seem to work around it.

Exception in thread "main" java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.lang.Double.parseDouble(Double.java:538) at com.company.Main.main(Main.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Instructions

Design a program that will prompt for and read in two numbers as strings. The numbers could be decimal numbers (double or float) or whole numbers (int). Convert these numbers from String to numeric. You can either choose the correct numeric type for the number of convert directly to double since it is the largest enclosing type. If the numbers are not valid, please inform the user and prompt again. After both valid numbers are read in, read in an operator (+, -, *, /). If the operator read in is not one of the allowed operators, inform the user and prompt again. Once everything is valid perform the indicated operation using the two numbers.

Do not use a try...catch block to intercept errors. All other options are open to you.

package com.company;

import java.util.Scanner;

    public class Main {

        public static void main(String[] args) {

            String sInput;
            String nInput;
            double dInput;

            String sInput2;
            String nInput2;
            double dInput2;

            boolean inputOK = false;
            String operator = "";

            int decCount;
            String operatorSelect;
            double total = 0;

            Scanner scanner = new Scanner(System.in);

            while (true) {
                do {
                    System.out.print("Enter first number: ");
                    //decimals count validation reset.
                    decCount = 0;
                    sInput = scanner.nextLine();
                    if (sInput == null) {
                        sInput = "0";
                    }
                    //purge !numerals || !decimals.
                    nInput = sInput.replaceAll("[^0-9.]", "");
                    //decimal count validation.
                    for (int i = 0; i < nInput.length(); i++) {
                        if (nInput.charAt(i) == '.') {
                            decCount = decCount + 1;
                        }
                    }
                    //break if input valid.
                    if (decCount <= 1) {
                        break;
                    }
                } while (true);
                dInput = Double.parseDouble(nInput);

                do {
                    System.out.print("Enter second number: ");
                    //decimals count validation reset.
                    decCount = 0;
                    sInput2 = scanner.nextLine();
                    //purge !numerals || !decimals.
                    nInput2 = sInput2.replaceAll("[^0-9.]", "");
                    //decimal count validation.
                    for (int i = 0; i < nInput2.length(); i++) {
                        if (nInput2.charAt(i) == '.') {
                            decCount = decCount + 1;
                        }
                    }
                    //break if input valid.
                    if (decCount <= 1) {
                        break;
                    }
                } while (true);
                dInput2 = Double.parseDouble(nInput2);
                while (inputOK == false) {
                    System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
                    operatorSelect = scanner.nextLine();
                    switch (operatorSelect) {
                        case "1":
                            total = dInput + dInput2;
                            inputOK = true;
                            operator = "+";
                            break;
                        case "2":
                            total = dInput - dInput2;
                            inputOK = true;
                            operator = "-";
                            break;
                        case "3":
                            total = dInput * dInput2;
                            inputOK = true;
                            operator = "*";
                            break;
                        case "4":
                            total = dInput / dInput2;
                            inputOK = true;
                            operator = "/";
                            break;
                        default:
                            System.out.println("Invalid input.");
                    }
                }
                System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
            }
        }
    }
2
So check for an empty string.rghome
Improved formatting, removed tag from title and updated tags. Its better to explain you code if it more complex than checking for a null or empty string. For checking the empty string use .isEmpty().Ram

2 Answers

1
votes

If you press enter, sInput is not null, it's an empty String.

sInput = scanner.nextLine();
if (sInput.equals("")) {
  sInput = "0";
} 
0
votes

The expression ^-?\d+(,\d+)*(\.\d+(e\d+)?)?$ will match a string that starts with an optional negative sign, one or more digits, optionally followed by a comma and more digits, followed by an optional fractional component which consists of a period, one or more digits, and another optional component, the exponent followed by more digits.

This is not the only solution as there can be many expressions that can match these sets of number strings.

I haven't optimized your code just added the regex check and empty check

import java.util.Scanner;

    public class Main {

    public static void main(String[] args) {

        String sInput;
        String nInput;
        double dInput;

        String sInput2;
        String nInput2;
        double dInput2;

        boolean inputOK = false;
        String operator = "";

        int decCount;
        String operatorSelect;
        double total = 0;

        Scanner scanner = new Scanner(System.in);

        while (true) {
            do {
                System.out.print("Enter first number: ");
                //decimals count validation reset.
                decCount = 0;
                sInput = scanner.nextLine();
                if (sInput.isEmpty()) {
                    System.out.println("Empty value Please Enter again");
                    continue;
                }
                if (!sInput.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
                    System.out.println("Invalid input Please Enter again");
                    continue;
                }
                break;

                //Not needed regex will take care of everything
//                //purge !numerals || !decimals.
//                nInput = sInput.replaceAll("[^0-9.]", "");
//                //decimal count validation.
//                for (int i = 0; i < nInput.length(); i++) {
//                    if (nInput.charAt(i) == '.') {
//                        decCount = decCount + 1;
//                    }
//                }
//                //break if input valid.
//                if (decCount <= 1) {
//                    break;
//                }
            } while (true);
            dInput = Double.parseDouble(sInput);

            do {
                System.out.print("Enter second number: ");
                //decimals count validation reset.
                decCount = 0;
                sInput2 = scanner.nextLine();
                if (sInput2.isEmpty()) {
                    System.out.println("Empty value Please Enter again");
                    continue;
                }
                if (!sInput2.matches("^-?\\d+(,\\d+)*(\\.\\d+(e\\d+)?)?$")) {
                    System.out.println("Invalid input Please Enter again");
                    continue;
                }
                break;
                //purge !numerals || !decimals.
//                nInput2 = sInput2.replaceAll("[^0-9.]", "");
//                //decimal count validation.
//                for (int i = 0; i < nInput2.length(); i++) {
//                    if (nInput2.charAt(i) == '.') {
//                        decCount = decCount + 1;
//                    }
//                }
//                //break if input valid.
//                if (decCount <= 1) {
//                    break;
//                }
            } while (true);
            dInput2 = Double.parseDouble(sInput2);
            while (inputOK == false) {
                System.out.println("Operator to select: \n1) +\n2) -\n3) *\n4) /\n");
                operatorSelect = scanner.nextLine();
                switch (operatorSelect) {
                    case "1":
                        total = dInput + dInput2;
                        inputOK = true;
                        operator = "+";
                        break;
                    case "2":
                        total = dInput - dInput2;
                        inputOK = true;
                        operator = "-";
                        break;
                    case "3":
                        total = dInput * dInput2;
                        inputOK = true;
                        operator = "*";
                        break;
                    case "4":
                        total = dInput / dInput2;
                        inputOK = true;
                        operator = "/";
                        break;
                    default:
                        System.out.println("Invalid input.");
                }
            }
            System.out.println(dInput + " " + operator + " " + dInput2 + " = " + total);
            break;
        }
    }
}