1

I am looking for the answer to how do I make my program run correctly. I want my program to recognize things other than doubles--- for example, if i placed in idk it would say, that is not a number instead of crashing.

my code:

import java.util.*;

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

        FunctionMain action = new FunctionMain();

         Scanner input = new Scanner(System.in);

        double answer = 0;
        double inputNu1, inputNu2;
        char operator;
        boolean end = false;

     while (! end ) {
            System.out.print(">>>");

            inputNu1 = input.nextDouble();
            operator = input.next().charAt(0);
            inputNu2 = input.nextDouble();        

    switch (operator) 
            {
        case '-': answer = action.Subtract(inputNu1, inputNu2);
                break;
        case '*': answer = action.Multiply(inputNu1, inputNu2);
                break;
        case '+': answer = action.Add(inputNu1, inputNu2);
                break; 
        case '/': answer = action.Divide(inputNu1, inputNu2);
               break;          
            }

        System.out.println(answer);             
        }       
        input.close();

    }

}



public class FunctionMain {

     double Subtract (double Nu1 , double Nu2)
    {
         return Nu1 + Nu2;

    }
    double Multiply (double Nu1 , double Nu2)
    {
        return Nu1 * Nu2;
    }
    double Add (double Nu1 , double Nu2)

    {
        return Nu1  + Nu2;
    }
    double Divide (double Nu1 , double Nu2)

    {  
        return Nu1 / Nu2;
    }

}
Isaac G Sivaa
  • 1,289
  • 4
  • 15
  • 32
Integral
  • 73
  • 2
  • 10
  • 1
    You are getting exceptions when you enter something other than a number correct? Do you know how exceptions work in Java? Alternatively, Scanner has a method called `hasNextDouble()`: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextDouble() – thatidiotguy Oct 20 '14 at 16:57
  • I do not know what you mean when you say "exceptions". When I am placing input with doubles as intended, there is not problem, but letters make it crash. I was thinking about using a Do While statement. Is that sensical? – Integral Oct 20 '14 at 17:02

3 Answers3

0

When you try to convert a String to a Double you get an exception, so you have to manage it as follows:

double n = 0.0;
try {
    n = input.nextDouble();
} catch (Exception e) {
    // there was an error, and here we can do whatever
    System.out.println( "It was not a number!" );
}

Learn more about excpetions: http://docs.oracle.com/javase/tutorial/essential/exceptions/

arutaku
  • 5,937
  • 1
  • 24
  • 38
  • You should not be catching generalized `Exception` when you know which one is going to be produced (`InputMismatchException`). – thatidiotguy Oct 20 '14 at 17:03
  • The code that makes the conversions should be surrounded by try { ... } catch. Have a quick look to the link in my post :-) – arutaku Oct 20 '14 at 17:08
0

Something like:

public static boolean isNumeric(String str)
{
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

or:

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

Check out: How to check if a String is numeric in Java

Community
  • 1
  • 1
Petro
  • 3,484
  • 3
  • 32
  • 59
0

The main idea here is to find the exception thrown by Scanner when a token retrieved does not match the expected type. If you enter a wrong input in your code, you would see java.util.InputMismatchException shown in the console. Therefore we could just use try{....}catch(java.util.InputMismatchException e){....} to catch this specific exception and add some user defined action.

I edited your CalculatorMain class, now if you enter input that could not be parsed to double, the console would output a warning and prompt you to enter new inputs again.

**Sample console output:**
>>>jdk
java.util.InputMismatchException
jdk IS INVALID INPUT
>>>test
java.util.InputMismatchException
test IS INVALID INPUT
>>>input 10
*
789
7890.0
import java.util.*;
public class CalculatorMain {
public static void main(String[] args) {
    FunctionMain action = new FunctionMain();
    double answer = 0;
    double inputNu1, inputNu2;
    char operator;
    boolean end = false;
    Scanner input = new Scanner(System.in);
    while (! end ) {

        System.out.print(">>>");
        try{
            inputNu1 = input.nextDouble();
            operator = input.next().charAt(0);
            inputNu2 = input.nextDouble();   
            switch (operator){
            case '-': answer = action.Subtract(inputNu1, inputNu2);
                break;
            case '*': answer = action.Multiply(inputNu1, inputNu2);
                break;
            case '+': answer = action.Add(inputNu1, inputNu2);
                break; 
            case '/': answer = action.Divide(inputNu1, inputNu2);
                break;          
            }

            System.out.println(answer); 

        }catch(InputMismatchException e){
            System.out.println(e.toString());
            System.out.println(input.next() + " IS INVALID INPUT");
        }
    } 
    input.close();
    }
}

For more information on Exceptions in Java -Catching and Handling Exceptions and Class InputMismatchException

C.X.Yang
  • 21
  • 4