如何修复udacityandroid开发过程中lab2的java计算器中的一个错误



我试图运行此代码,但它不起作用。

您应该创建一个具有基本功能的计算器。

创建一个计算器类,它有sum、减法、除法和乘法方法,所有这些方法都接受两个int参数并返回结果int

示例:当sum方法被称为sum(5,6(时,它应该返回11,这是5和6 的总和

我该怎么修?

class MyCalculator {
int input1 = 15;
int input2 = 5; 
public float sum() {
int sum = input1 + input2;
return sum;
}
public float divid() {
// TODO: write java code to calculate the average for all input variables
int divid = (input1 / input2);
return divid;
}
public float subtract() {
// TODO: write java code to calculate the average for all input variables
int subtract = (input1 - input2);
return subtract;
}
public float multiply() {
// TODO: write java code to calculate the average for all input variables
int multiply = (input1 * input2);
return multiply;
}
}

它给了我这个错误

method sum in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method divid in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method subtract in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method multiply in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length

在我们的每个函数声明中,类型是"float",但返回的是"int"。所以最好将两者更新为相同。以下是代码更改

public float sum() {
float sum = input1 + input2;
return sum;
}
public float divid() {
// TODO: write java code to calculate the average for all input variables
float divid = (input1 / input2);
return divid;
}
public float subtract() {
// TODO: write java code to calculate the average for all input variables
float subtract = (input1 - input2);
return subtract;
}
public float multiply() {
// TODO: write java code to calculate the average for all input variables
float multiply = (input1 * input2);
return multiply;
}

然后试试

// TODO create class MyCalculator with sum, divid, subtract, multiply
public class MyCalculator {
public int sum(int x,int y){
return x+y ;
}
public int subtract(int x,int y){
return x-y;
}
public int multiply(int x,int y){
return x*y;
}
public int divid(int x,int y){
return x/y;
}
}

您可以使用此代码来解决实验室

// TODO create class MyCalculator with sum, divid, subtract, multiply
class MyCalculator {

int num1 = 5;
int num2 = 6;

public int sum(int num1, int num2){
return num1+num2;
}

public int subtract(int num1, int num2){
return num1-num2;
}

public int multiply(int num1, int num2){
return num1*num2;
}  

public int divid(int num1, int num2){
return num1/num2;
}
}

相关内容

最新更新