Reputation: 81
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:
Upvotes: 0
Views: 84
Reputation: 11344
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);
}
}
}
Upvotes: 3