-1

I don't know why I am getting this error of -first type: java.lang.String second type: int.... Its a basic calculator program using java

public static void  main(String[] args){
    System.out.println("Welcome to the calculator");

    Scanner input = new Scanner(System.in);
    System.out.println("Enter your first inter number: ");
    String k = input.next();
    System.out.println("Enter second inter number: ");
    String l = input.next();
    int a =Integer.valueOf(k);
    int b =Integer.valueOf(l);
    String prompt = "Enter 1 for addition, 2 for subtraction, 3 for multiplication," +
            " 4 for division, 5 for remainder between two numbers";
    System.out.println(prompt);
    int z = input.nextInt();
    if (z == 1){
        System.out.println("Addition of two numbers: "+a + b);}
    else if (z == 2){
        System.out.println("Subtraction of two numbers: " +a - b);}
    else if (z == 3){
        System.out.println("Multiplication of two numbers: "+a * b); }
    else if (z == 4){
        System.out.println("Division of two numbers: "+a / b);}
    else if (z == 5){
        System.out.println("remainder of two numbers: "+a % b);}
    else{
        System.out.println("Invalid input");

    }

}

The error is in :

else if (z == 2){
        System.out.println("Subtraction of two numbers: " +a - b);}
0

1 Answer 1

1

When you do "Subtraction of two numbers: " +a, Java concatenates the String and integer to form a String. Then, when it reaches the - b segment, it thinks you're trying to subtract an integer... from a String. If you put your math operations in parenthesis like this: (a - b) your code should work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.