FRP7 FRP7 - 13 days ago 5
Java Question

Need help in my java calculator

i started studying java recently and i tried to program a calculator but it gives me error (and i don't understand why it happens).

PS: Sorry for my bad english

package pkg2;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Write a number: ");
int first = reader.nextInt();
System.out.println("Write another number: ");
int second = reader.nextInt();
System.out.println("Write an operator: ");
char operator = reader.nextInt();
if(operator == '+') {
System.out.println(first + second);
}
else if(operator == '-') {
System.out.println(first - second);
}
else if(operator == '*') {
System.out.println(first * second);
}
else if(operator == '/') {
System.out.println(first / second);
}
}
}


The error is:

enter image description here

Answer

When you prompt for an operator, you are trying to read a int, instead of a char. Here's how you should do it:

package pkg2;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Write a number: ");
        int first = reader.nextInt();
        System.out.println("Write another number: ");
        int second = reader.nextInt();
        System.out.println("Write an operator: ");
        char operator = reader.next().charAt(0);
        if(operator == '+') {
            System.out.println(first + second);
        }
        else if(operator == '-') {
            System.out.println(first - second);
        }
        else if(operator == '*') {
            System.out.println(first * second);
        }
        else if(operator == '/') {
            System.out.println(first / second);
        }
    }
}
Comments