有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从Main中的嵌套循环更新Main中的数组。我如何分配它的值?

所以,我在编写程序时,突然遇到了一个问题,我的三个数组打印为null、0和null

程序从文件中读取值,并根据迭代次数将它们分配给三个数组

这是我的密码:

String  mushroom []= new String [10];
int  weight [] = new int [10];
String  cooking[] = new String [10];

FileReader fr = new FileReader ("7J_Mushrooms.csv");
BufferedReader br = new BufferedReader (fr);
System.out.println("Mushroom\t\tWeight\t\tCooking\n=======================================================");
String line = "";


while ((line = br.readLine()) != null){

    String [] temp = line.split(",");
    for (int i = 0; i < temp.length; i++){  
        if(i == 0){
            mushroom[i] = temp[i];
        }
        else if (i == 1){
            weight[i] = Integer.parseInt(temp[i]);  
        }
        else{
            cooking[i] = temp[i];
        }
    }               
 }

// This bit just sorts them by weight in ascending order like a parallel array
for (int i = 0; i < weight.length-1; i++){
    for (int j = 0; j < weight.length-1;j++){
        if (weight[j] > weight[j+1]){

            int temp = weight [j];
            String tempMush = mushroom [j];
            String tempCook = cooking [j];
            weight[j] = weight[j+1];
            mushroom[j] = mushroom[j+1];
            cooking[j] = cooking[j+1];
            weight[j+1] = temp;
            mushroom[j+1] = tempMush;
            cooking[j+1] = tempCook;
        }
    }
}

for (int i = 0; i < weight.length; i++){
    System.out.print(mushroom[i] + "\t\t" + weight[i] + "\t\t" + cooking[i] + "\n");
}

当我在for循环内部打印数组的值时,值是正确的,但是在while循环外部,代码被打印为null、null和0。然而,最后三个值已打印出来,但我确信这与我的问题有关

无论如何,我相信这与范围有关

经过一些搜索,我发现java是“按值传递”而不是“按引用传递”。我并不真正理解这个原理,但据我所知,它特别影响方法,但我所有的代码都在一个方法main下。我尝试在for循环内部和外部使用return,但它也不起作用


共 (2) 个答案

  1. # 1 楼答案

    你只写了每个蘑菇的前三个元素,烹饪和重量。 作为

        i < temp.length,   i <= 3
    
  2. # 2 楼答案

    您最初读取中的值的方式似乎很不正确:您将相应的weightcooking放入与实际mushroom不同的索引中,并且您以完全错误的方式使用索引i。应该是的

    int i = 0;
    while ((line = br.readLine()) != null){
    
        String[] temp = line.split(",");
        if(temp.length == 3)
            mushroom[i] = temp[0];
            weight[i] = Integer.parseInt(temp[1]);  
            cooking[i] = temp[2];
        } else {
            // some error handling
        }         
        i++;
     }
    

    “当我打印for循环内部数组的值时,值是正确的”是错误的-如果您检查temp值是正确的,但是mushroomweightcooking从未正确地用代码填充

    进一步说明:

    • 尝试使用自定义类来保存关联的值,而不是处理3个数组,它们之间有着神奇的关联。然后对该类的实例数组进行排序