Java 如何使用我创建的方法修改数组中对象的一个属性?
我正在尝试使用我创建的ModifyPhonePrices修改我手机类中对象的价格,但无论何时调用该方法,该方法都不起作用。请帮助Java 如何使用我创建的方法修改数组中对象的一个属性?,java,Java,我正在尝试使用我创建的ModifyPhonePrices修改我手机类中对象的价格,但无论何时调用该方法,该方法都不起作用。请帮助 import java.util.Random; public class ModifyCellPhones { public static double ModifyPhonePrices (double[][] cellarr, double ov, double nv) { int ctr=0, i, j; f
import java.util.Random;
public class ModifyCellPhones {
public static double ModifyPhonePrices (double[][] cellarr, double ov, double nv)
{
int ctr=0, i, j;
for (i=0; i < cellarr[i].length ; i++)
{
for (j=0; j < cellarr[j].length; j++)
{
if (cellarr[i][j] == ov)//if the content of the index i in the array
{ //equals that of the old value then
cellarr[i][j] = nv;//it will be replaced by the new value
ctr++;//keeps track of the changes performed
System.out.println("The value changed was found at index" + "[" + i + "]" + "[" + j + "]");
}
}
}
return ctr;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int i, j, counter = 0;
Random rand = new Random();//random object that will assign random values to the phones that are uninitialized
CellPhone [][] cp = new CellPhone [10][10];//creation of two-dimensional array
//creating 90 cellphones using the for loop
for (i=0 ;i < 10; i++)
{
for (j=0; j < 10; j++)
{
cp[i][j] = new CellPhone ("Blackberry",569874132,300.00);
counter++;
System.out.println(cp[i][j]);
}
}
System.out.println();
System.out.println("Here are the contents of the array; only the prices of the contents are shown:");
System.out.println();
//setting the prices using the random class
for (i=0; i < 10; i++)
{
for (j=0; j < 10; j++)
{
cp[i][j].setprice(rand.nextInt(300));
System.out.printf("%8.2f",cp[i][j].getprice());
}
System.out.println();
}
//creating a another array to copy the price content of the cellphone array
double [][] arr = new double [10][10];
for (i=0; i<10; i++)
{
for (j=0; j<10; j++)
{
arr[i][j] = cp[i][j].getprice();
}
}
//modifying values using the ModifyPhonePrices method created
counter = ModifyCellPhones.ModifyPhonePrices(arr[][] ,150.00,200.00);
if (counter > 0)
{
System.out.println (counter + "changes are made.");
}
}
}
import java.util.Random;
公营改装手机{
公共静态双修改电话价格(双[][]Celler、双ov、双nv)
{
int ctr=0,i,j;
对于(i=0;i
for (i=0; i < cellarr[i].length ; i++)
{
for (j=0; j < cellarr[j].length; j++)
(i=0;i
{
对于(j=0;j
应该是
for (i=0; i < cellarr.length; i++)
{
for (j=0; j < cellarr[i].length; j++)
for(i=0;i
我认为正在发生的事情(尽管您没有指定)是当j
到达10
时,Cell[j]
抛出一个ArrayIndexOutOfBoundsException
您永远不应该说“它不工作”。您应该始终说出发生了什么,并包括确切的错误消息和所需的行为。您的问题的一部分(正如所指出的)是您在循环中使用了错误的哨兵值:
for (i=0; i < cellarr[i].length ; i++) {
for (j=0; j < cellarr[j].length; j++) {
而不是
counter = ModifyPhonePrices(arr[][], 150.00, 200.00);
最后,对于货币来说,
double
是个坏主意。看看
这些更改应该会产生工作代码
counter = ModifyPhonePrices(arr, 150.00, 200.00);
counter = ModifyPhonePrices(arr[][], 150.00, 200.00);