不能在 for 循环中向我的数组添加元素。

huangapple go评论71阅读模式
英文:

cannot append to my array during a for loop

问题

我目前正在使用Aleks Rudenko的书学习JAVA,作为JAVA的新手,我仍然无法解决简单的编译错误。我尝试创建一个简单的代码,它接受一个数组X,并将其每个单项与Y相乘。最终,数组*X应按如下方式打印输出:

public class CurrencyConverter {   
    double[] answers = new double[] {};
    public double[] Times2(double[] x, double y) {
        for (int i = 0; i < x.length; i++) {
            answers[i] = x[i] * y;
        }
        return answers;
    }
    public static void main(String[] args) {
        CurrencyConverter cc = new CurrencyConverter();
        double[] rates = new double[] {63, 3.0, 3.0, 595.5, 18.0, 107.0, 2.0, 0.0};
        double[] result = cc.Times2(rates, 2);
        for (double value : result) {
            System.out.println(value);
        }
    } 
}

错误信息如下:

错误:找不到符号
                     answers.add(x[i]*y);
                            ^
      符号:   方法add(double)
      位置: 类型为double[]的变量answers
    1个错误

我无法弄清楚这个编译错误的原因。谢谢帮助!

英文:

I am currently learning JAVA using Aleks Rudenko book, and as a newbie in JAVA I still cannot figure out simple compilation errors. I tried to create a simple code that takes an array X and multiply every single term of it by Y. Finally, the array*Y should be printed out as follows:

   public class CurrencyConverter {   
       double[] answers = new double[] {};
       public double[] Times2 (double[] x, double y) {
	       for (int i=1; i&lt;x.length+1;i++) {
		     answers.add(x[i]*y);
	       }
       return answers;
       }
       public static void main(String[] args) {
       CurrencyConverter cc = new CurrencyConverter();
       double [] rates= new double[] {63,3.0,3.0,595.5,18.0,107.0,2.0,0.0};
	   System.out.println(cc.Times2(rates,2));
       } 
    }

the error message is

error: cannot find symbol
                 answers.add(x[i]*y);
                        ^
  symbol:   method add(double)
  location: variable answers of type double[]
1 error 

I cannot figure out what is the reason for this compilation error. Thanks for the help !

答案1

得分: 1

add 在数组中未定义。如果您想要添加元素,请使用 List。

有几种修复您的代码的方法:

a) 使用 List:

import java.util.*;

List<Double> list = new ArrayList<Double>();

public List<Double> Times2(double[] x, double y) {
    for (int i = 0; i < x.length; i++) {
        list.add(x[i] * y);
    }
    return list;
}

b) 不要添加元素,只需将它们写入数组:

double[] answers;

public double[] Times2(double[] x, double y) {
    answers = new double[x.length];
    for (int i = 0; i < x.length; i++) {
        answers[i] = x[i] * y;
    }
    return answers;
}

另外,注意数组索引越界的问题。第一个元素的索引为 0,最后一个元素的索引为 length - 1

还有最后一点,您可能会遇到打印结果的问题。
如果您想使用 List,请使用 System.out.println(cc.Times2(...).toString());,如果您想使用数组,请使用 System.out.println(Arrays.toString(cc.Times2(...)));

英文:

add is not defined for arrays. If you want to add elements, use List.

There are several ways to fix your code:

a) use List:

import java.util.*;

List&lt;Double&gt; list = new ArrayList&lt;Double&gt;();

public List&lt;Double&gt; Times2 (double[] x, double y) {
    for (int i=0; i&lt;x.length;i++) {
      list.add(x[i]*y);
    }
    return list;
}

b) Don't add elements, just write them into array:

double[] answers;

public double[] Times2 (double[] x, double y) {
	answers = new double[x.length];
    for (int i=0; i&lt;x.length;i++) {
      answers[i] = x[i]*y;
    }
    return answers;
}

..Also, watch out for the array index out of bounds. First element has index 0 and last item has index length - 1.

And one last thing, you will probably encounter problem with printing your results.
If you want to use list, use System.out.println(cc.Times2(...).toString()); and if you want to use array, use System.out.println(Arrays.toString(cc.Times2(...)));

答案2

得分: 1

最好使用 while 循环,而不是 for 循环,适用于这种情况。并且使用一个向量:

Vector<Object> answers = new Vector<Object>();
英文:

Better to use a while loop, instead of a for loop, for this use case. And use a Vector:

   Vector&lt;Object&gt; answers = new Vector&lt;Object&gt;();

答案3

得分: 1

在Java中,数组没有任何方法。您通过索引访问元素。您的代码应如下所示:

public static class CurrencyConverter {

    public double[] Times2(double[] x, double y) {
        double[] answers = new double[x.length];
        for (int i = 0; i < x.length; i++) {
            answers[i] = x[i] * y;
        }
        return answers;
    }

}

请注意,for循环以i为0开始。数组的第一个索引始终是0,而不是1。在方法内部初始化了answers数组,因为最好将变量对于不需要它们的内容隐藏(作用域限定)。它也已初始化为所需的大小。

这里还有一些答案建议基于java.util.AbstractCollection使用某些内容。虽然您可以这样做,但在像这样简单的情况下,没有必要增加额外的开销。

英文:

Arrays in java don't have any methods. You access stuff by index. Your code should look

public static class CurrencyConverter {

    public double[] Times2(double[] x, double y) {
        double[] answers = new double[x.length];
        for (int i=0; i &lt; x.length; i++) {
            answers[i] = x[i] * y;
        }
        return answers;
    }

}

Notice that the for loop starts with i as 0. the first index of an array is always 0, not 1. the answers array is init'ed inside the method as it's best to keep variables hidden (scoped) from things that don't need them. it's also init'ed with the size it needs to be.

Some of the other answers here say to use stuff based on java.util.AbstractCollection. While you could but there's no good reason for extra overhead for something simple like this.

答案4

得分: 1

你正在对一个 数组 使用 . 点操作符answers 是一个数组,它的值可以像这样访问:answers[0] -> 第一个元素 或者 answers[9] -> 第9个元素。如果 answers 是一个具有名为 status 的变量的对象,那么你可以通过 answers.status 来访问 status。

类似地,如果 answers 有一个名为 bestAnswer() 的方法,你可以通过 answers.bestAnswer() 来访问它。

如果你想在一个数组中保存一组你自定义类型 Answer 的对象,你需要首先实例化每个 Answer 对象,然后将它添加到 answers 数组中,如下所示:

Answer firstAnswer = new Answer(); 
Answer secondAnswer = new Answer();
...
 
answers[0] = firstAnswer;
answers[1] = secondAnswer;
...
英文:

You are using . dot operator on an array. answers is an array and its values can be accessed like answers[0] -> first element or answers[9] -> gives 9th element. Had answers been an object with say a variable called status, then you would access status from answers as answers.status

Similar if answers have method say bestAnswer() then you would access it as answers.bestAnswer()

And if you want to hold a bunch of objects of your custom type Answer in an array then you would instantiate each Answer object first and add it to the array answers array as:

Answer firstAnswer = Answer(); 
Answer secondAnswer = Answer();
...
 
answers[0] = firstAnswer;
answers[1] = secondAnswer;
...


</details>



huangapple
  • 本文由 发表于 2020年5月5日 08:01:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61603614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定