java - 通过扫描仪在java中使用运算符

标签 java

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)

最佳答案

您可以通过删除第 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);
    }
}

希望这对您有帮助。

关于java - 通过扫描仪在java中使用运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39096030/

相关文章:

java - 如何在 Java 中禁用 ButtonGroup 内的 JRadioButton

java - 使用 Spring Boot 设置 Camel 和 Activemq

java - 如何使用 HashMap 写入和读取文件?

java - Java 中的逐行打印

java - 使用 Jackson 从 JSON 树中的特定节点映射对象

java - java.lang.ArrayIndexOutOfBoundsException错误Hadoop MapReduce进程

java - 无法在 Spring 服务中使用 ReposiotryResource 端点

java - 没有为 imageView javafx 加载 CSS 类

Java:错误:变量可能尚未初始化

java - equals() 的实现 : compare against implemented interface or implementing class?