gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:34:45 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com