0
public class arithmcalc {

public static void main(String[] args) {
    int operand1;
    int operand2;
    char operator;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter operan1 operand2 and operator one by one");
    operand1 = sc.nextInt();
    sc.nextLine();
    operand2 = sc.nextInt();
    sc.next();
    operator = sc.findInLine(".").charAt(0);

    int result = 0;

    switch (operator) {
        case '+':
            result = operand1 + operand2;
            break;
        case '-':
            result = operand1 - operand2;
            break;
        case '*':
            result = operand1 * operand2;
            break;
        case '/':
            result = operand1 / operand2;
        default:
            System.out.println("illegal operand");
    }
  }
}
Exception in thread "main" java.lang.NullPointerException
at javaapplication67.arithmcalc.main(arithmcalc.java:24)
Termininja
  • 6,620
  • 12
  • 48
  • 49
  • Why are you calling `sc.nextLine()` and `sc.next()` in between your operands? – byxor Aug 23 '16 at 08:29
  • Your `Scanner` use is inconsistent and probably the root of your problem. If the input format is "x y operator", you'd better just call `sc.nextInt()` twice for the numbers then `sc.next()` for the operator. – Aaron Aug 23 '16 at 08:30

1 Answers1

1

You can avoid the error by removing line 10 ans 12 and modifing the code as given below.

import java.util.Scanner;

public class arithmcalc {

    public static void main(String[] args) {
        int operand1;
        int operand2;
        char operator;
        Scanner sc = new Scanner(System.in);
        System.out.println("enter operan1 operand2 and operator one by one");
        operand1 = sc.nextInt();
        operand2 = sc.nextInt();
        operator = sc.next().charAt(0);

        int result = 0;

        switch (operator) {
            case '+':
                result = operand1 + operand2;
                break;
            case '-':
                result = operand1 - operand2;
                break;
            case '*':
                result = operand1 * operand2;
                break;
            case '/':
                result = operand1 / operand2;
            default:
                System.out.println("illegal operand");
        }
     System.out.println("Result : " + result);
    }
}

Hoper this was helpful.

Kamidu Punchihewa
  • 1,241
  • 10
  • 18