2016-08-23 4 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

Warum rufen Sie 'sc.nextLine()' und 'sc.next()' zwischen Ihren Operanden auf? – byxor

+0

Ihr 'Scanner' ist inkonsistent und wahrscheinlich die Wurzel Ihres Problems. Wenn das Eingabeformat "x y operator" lautet, rufen Sie einfach 'sc.nextInt()' zweimal für die Zahlen und dann 'sc.next()' für den Operator auf. – Aaron

Antwort

1

können Sie den Fehler vermeiden, indem Sie Zeile entfernen 10 am 12 und modifing den Code wie unten angegeben.

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); 
    } 
} 

Hope das war hilfreich.

+0

danke @ Kachiex –

+0

Gern geschehen. @pranjalsingh Wenn dies die Antwort ist, die Sie gesucht haben, markieren Sie diese als akzeptierte Antwort. Prost. – Kamidu