gpt4 book ai didi

java - 如何在我的java计算器中返回int?

转载 作者:行者123 更新时间:2023-12-02 05:47:12 25 4
gpt4 key购买 nike

如果我的标题不够具体,我很抱歉。我正在尝试创建一个计算器。您输入:“手术”“数字1”“数字2”

你就会得到答案。

目前,我从以下代码中收到以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
This method must return a result of type int

at LessonOne.Main.calcu(Main.java:17)
at LessonOne.Main.main(Main.java:13)

我的输入是“+”、“5”、“5”

请告诉我我做错了什么。我花了几个小时编辑这个,这是我想出的最好的。我完全陷入困境。

package LessonOne;

import java.util.Scanner;

public class Main {

public static Scanner s = new Scanner(System.in); //<-- DO NOT TOUCH

public static void main(String[] args) {
String oper = getStr(); //Enter your operator
int numberOne = getInteger(); //Enter your first number
int numberTwo = getInteger(); //Enter your second number
int total = calcu(oper, numberOne, numberTwo); //Perform calculation
System.out.println(total); //Print the total
}

static int calcu(String oper, int numberOne, int numberTwo) {
if (oper.equals('+')) {
int total = add(numberOne, numberTwo);
return total;
} else if (oper.equals('-')) {
int total = sub(numberOne, numberTwo);
return total;
} else if (oper.equals('*')) {
int total = multi(numberOne, numberTwo);
return total;
} else if (oper.equals('/')) {
int total = div(numberOne, numberTwo);
return total;
}

}

static int add(int numberOne, int numberTwo) {
return int total = numberOne + numberTwo;


}

static int multi(int numberOne, int numberTwo) {
return int total = numberOne * numberTwo;

}

static int sub(int numberOne, int numberTwo) {
return int total = numberOne - numberTwo;

}

static int div(int numberOne, int numberTwo) {
return int total = numberOne / numberTwo;
}

public static String getStr() {//<-- DO NOT TOUCH
return s.nextLine();//<-- DO NOT TOUCH
}//<-- DO NOT TOUCH

public static int getInteger() { //<-- DO NOT TOUCH
return s.nextInt(); //<-- DO NOT TOUCH
} //<-- DO NOT TOUCH

}

最佳答案

问题是,如果操作数不是您正在测试的操作数之一,您的方法 calcu() 不会返回任何内容。

在最后一次测试后添加返回语句,或者引发异常。我建议抛出未经检查的异常:

throw new IllegalArgumentException("Unknown operation " + oper); 

关于java - 如何在我的java计算器中返回int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952068/

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