我正在尝试使用我创建的ModifyPhonePrices来修改手机类中对象的价格,但是每当我调用它时该方法都无法正常工作。请帮助!
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.");
}
}
}
答案 0 :(得分:0)
我相信
for (i=0; i < cellarr[i].length ; i++)
{
for (j=0; j < cellarr[j].length; j++)
应该是
for (i=0; i < cellarr.length; i++)
{
for (j=0; j < cellarr[i].length; j++)
我认为正在发生的事情(尽管您未指定)是j
到10
时,cellar[j]
会引发ArrayIndexOutOfBoundsException
。
你永远不应该说“它不起作用”。你应该总是说出会发生什么,并包括确切的错误信息和所需的行为。
答案 1 :(得分:0)
您的部分问题(也由pbabcdefp指出)是您在循环中使用了错误的哨兵值:
for (i=0; i < cellarr[i].length ; i++) {
for (j=0; j < cellarr[j].length; j++) {
应该是
for (i=0; i < cellarr.length; i++) {
for (j=0; j < cellarr[i].length; j++) {
接下来,您将从ModifyPhonePrices
返回一个double而不是一个int(根据惯例,它应该是modifyPhonePrices
)。这是所做更改次数的整数计数,double
只是没有意义(特别是假设ctr
被声明为int
)。
接下来,如imad3v所述,您的方法调用应为
counter = ModifyPhonePrices(arr, 150.00, 200.00);
而不是
counter = ModifyPhonePrices(arr[][], 150.00, 200.00);
最后,货币的double
是一个坏主意。看看BigDecimal。
这些改变应该产生工作代码。