【问题标题】:Writing a method in java using an array and objects使用数组和对象在java中编写方法
【发布时间】:2021-06-14 08:06:59
【问题描述】:

我是 Java 新手,我被这个问题困住了:

“创建第二个 add() 方法,该方法具有双精度数组的单个参数,并在方法内部添加数组的值,将结果作为双精度返回。示例测试数据:

double[] dblArr = {11.82,88.23,33};

到目前为止,我有一个单独的类文件:

public double add(double[] values) {
    int sum = 0;
    for (double i : values)
        sum += i;

     return sum;
}

这是将数组相加并返回总和的方法。

这是我在“主”文档中调用该方法的代码

double dblArr;
utils.print("Please enter an array of 5 numbers: ");
dblArr = input.nextDouble();

double sum = calc.add(dblArr);

System.out.println(dblArr);

我知道我的范围很广,因此非常感谢您提供一些建议,谢谢

“calc”是我用来调用其他文档的东西

计算 calc = new Calculate();

【问题讨论】:

  • 看起来您正在呼叫calc,就好像它是static。如果您不需要创建calc 的实例,请将static 添加到前面:public static add(double[]...
  • 还有什么问题?你遇到了什么错误?发生了什么事情并没有像您期望的那样发生?请将其编辑到您的帖子中,谢谢。
  • int sum = 0; 应该是 double sum = 0; - 而你的 dblArr 应该是 double[](而不是 double)。

标签: java arrays class object methods


【解决方案1】:

你已经完成了大部分的工作,你只需要使用一个双精度数组来收集输入,并且你需要使用一个循环来将所有的 inpets 保存到数组中:

//use an array instead of a single double
double[] dblArr = new double[5];
int inputs = 0;
//Use a loop to gather 5 inputs
while(inputs < 5){
    utils.print("Please enter the next of 5 numbers: ");
    dblArr[inputs] = input.nextDouble();
    inputs++;
}

//We have changed the add method to static, so you can just use `add(dblArr)` instead of making an instance of the class with the add method
double sum = add(dblArr);

//Finally print out the sum result not the dblArr array
System.out.println("The total is " + sum);

那就把方法改成static,这样就可以直接调用了:

//Add static to this line as shown, because we don't need an instance of this method
public static double add(double[] values) {
    int sum = 0;
    for (double i : values)
        sum += i;

    return sum;
}

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    相关资源
    最近更新 更多