2016-08-23 3 views
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) 
+0

Почему вы вызываете 'sc.nextLine()' и 'sc.next()' между вашими операндами? – byxor

+0

Использование 'Scanner' является непоследовательным и, вероятно, является причиной вашей проблемы. Если входной формат является «оператором x y», вам лучше просто называть 'sc.nextInt()' дважды для чисел, а затем 'sc.next()' для оператора. – Aaron

ответ

1

Вы можете избежать этой ошибки, удалив линию 10 анс 12 и код необходимости модифицировать, как указано ниже.

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 это было полезно.

+0

thankyou @ kachiex –

+0

Добро пожаловать. @pranjalsingh, если это ответ, который вы искали, отметьте это как принятый ответ. Приветствия. – Kamidu

Смежные вопросы