0
Scanner input = new Scanner(System.in);

        System.out.println("Enter a value : ");
        String s3 = input.next();
        System.out.println("Enter another value: " );
        String s5 = input.next();

        String s = ("1= add, 2 = subtract");
        int op = Integer.parseInt(s);
        double result=0;
        switch (op) {
        case 1:
            result = addValues(s3, s5);
            break;
        case 2:
             result = subtractValues(s3, s5);
        default:
            System.out.println("Incorrect");
            break;
        }

        addValues(s3, s5);

        subtractValues(s3, s5);
    }

    private static double subtractValues(String s3, String s5)
            {
        double d1 = Double.parseDouble(s3);
        double d2 = Double.parseDouble(s5);

        double result = d1-d2;
        return result;
    }

    private static double addValues(String s3, String s5)
         {
        double d1 = Double.parseDouble(s3);
        double d2 = Double.parseDouble(s5);

        double result = d1+d2;
        return result;


    }
    }

I have the above code and its thorwing an exception of numberformatException. What is wrong with this code .. kindly help me out.

2
Contributors
4
Replies
13
Views
4 Years
Discussion Span
Last Post by engrjd91
0

I have the above code and its thorwing an exception of numberformatException. What is wrong with this code .. kindly help me out.

Which values did you enter as input?

Edit: look closely at the following two lines of code:

String s = ("1= add, 2 = subtract");
int op = Integer.parseInt(s);

You are trying to parse the String 1= add, 2 = subtract as an int, and then get thrown a NumberFormatException in your face because that String is not a valid number.

Edited by mvmalderen

0

so whats the perfert way to do it now ?
i want these options to be shown..
and user should input one of the options as an integer

0

Print the options the user can choose from, and prompt the user to choose one of them.
Without error checking the code could look as follows:

System.out.println("1 = add, 2 = subtract");
System.out.println("pick an option> ");
int choice = Integer.parseInt(input.nextLine());
// ...

Edited by mvmalderen

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.