0

i'm really new to Java and i'm trying to make a basic calculator, I've managed to get it to work and produce a double as i desired. My problem is that i want it to provide an error message if user inputs the wrong data type e.g. String

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    double n1, n2;
    String n3;
    Scanner inp = new Scanner(System.in);


    System.out.print("Enter first value: ");
    String inp1 = inp.nextLine();
    n1 = Double.parseDouble(inp1);


    System.out.print("Enter Second Value: ");
    String inp2 = inp.nextLine();
    n2 = Double.parseDouble(inp2);


    System.out.print("Enter Operation: ");
    String inp3 = inp.nextLine();

    switch (inp3) {

        case "+":
            System.out.println("The result is: " + (n1 + n2));
            break;
        case "-":
            System.out.println("The result is: " + (n1 - n2));
            break;
        case "*":
            System.out.println("The result is: " + (n1 * n2));
            break;
        case "/":
            System.out.println("The result is: " + (n1/n2));
            break;
        default:
            System.out.println("Invalid Operation! \nPlease use '-,+,*,/' ");

    }

}

}

Here's my code at the moment, im open to any constructive criticism to improve my code. I can't seem to figure out a way to solve my problem! Thanks for any help :)

Paloking
  • 41
  • 4

6 Answers6

0

The parseDouble:

public static double parseDouble(String s)

throws NumberFormatException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

So just surround every n1 = Double.parseDouble(inp1); with try catch and in catch block, print your error message.

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
0

Use exceptions.

Do this,

System.out.print("Enter first value: ");
String inp1 = inp.nextLine();
try{
    n1 = Double.parseDouble(inp1);
}
catch(NumberFormatException exc){
    System.err.println("The input was not a valid double");
}

When parseDouble() fails to parse the given String to a double it throws a NumberFormatException. The above code checks if this exception was thrown inside the try block and "catch"s it and deals with the exception in the catch block. More on this here

Learn more about Exceptions here

Ghazanfar
  • 1,419
  • 13
  • 21
0
  1. Dont use variable names like n1,n2,n3 etc. It will confuse you in larger projects.
  2. On parsing Doubles use

    try{
        n2 = Double.parseDouble(inp2);
    } catch(NumberFormatException numberFormatException){
        System.out.println("Wrong number format of input: "+inp2+". Exception:" +numberFormatException.getMessage());
        return;
    }
    
  3. If you don't want to use Exceptions for checking if input String is number format you can always use some libs like apache commons. In this case code would look like this

    if (StringUtils.isNumeric(inp2)) {
        n2 = Double.parseDouble(inp2);
    } else {
        System.out.println("Wrong number format of input: " + inp2);
        return;
    }
    

More Information here: How to check if a String is numeric in Java

Community
  • 1
  • 1
graczun
  • 572
  • 1
  • 5
  • 16
0

for simplicity you can have a method that keep asking for input until right one is achieved, for example:

public double askForDouble(Scanner input){
  while(true){ 
   System.out.println("enter a good double:" ) ;
   try{
     return Double.parseDouble(input.nextLine());
   }catch(Exception e){
    System.out.println("not a good double try again...");

   }
  }
}

then in your main method you can replace

String inp1 = inp.nextLine();
n1 = Double.parseDouble(inp1);

with

n1 = askForDouble(inp);

same procedure can be applied for your mathematical operations(e.g. + , - ) too

nafas
  • 5,283
  • 3
  • 29
  • 57
0

The method parseDouble can throw following exceptions:

  1. NullPointerException - if the string is null
  2. NumberFormatException - if the string does not contain a parsable double.

You may need to surround your code with try/catch like:

try {
      String inp1 = inp.nextLine();
      if(null != inp1 ) {
         n1 = Double.parseDouble(inp1);
      }
} catch (NumberFormatException e) {
    // Handle NFE.
}
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
0

I think you want to handle exception after wrong input. I see that you parse String input to double, in that case there should be cached NumberFormatException from that parse method. And you can from there handle that case where user input wrong String.

Or you read numbers from console by using inp.nextDouble(), in this case there could appear InputMismatchException and you can handle this exception.

edasssus
  • 331
  • 4
  • 15