方法中的数组元素并将值返回到数组

时间:2015-04-06 04:31:21

标签: java arrays methods

我正在为一个产品(没有特定项目)程序编写代码。这是我需要帮助学习的内容:

我需要取两个数组元素(数字[4]和数字[5]),制作一个方法,在该方法中将它们一起添加,然后返回并将它们存储回数组元素号[6]。

如何创建一个可以读取已存储在数组中的信息的方法?

这是我的代码:

// This is an inventory program part 1 "Section 1"
public class inventory {

    public static void main(String[] args) {

        String[] inventory = new String[8]; 

        inventory[0] = "hammer"; 
        inventory[1] = "shovel";
        inventory[2] = "Product#";
        inventory[3] = "Product Name";
        inventory[4] = "Units In Stock";
        inventory[5] = "Price";
        inventory[6] = "Total Value Of Product";
        inventory[7] = "Total Value of Entire Inventory";

        float[] numbers = new float[7];

        numbers[0] = 1585;// hammers in stock
        numbers[1] = 900;// shovels in stock
        numbers[2] = (float) 7.48;// hammer price
        numbers[3] = (float) 9.98;// shovel price
        numbers[4] = ( numbers[0] * numbers[2] );// total value of hammers in inventory
        numbers[5] = ( numbers[1] * numbers[3] );// total value of shovels in inventory
        numbers[6] = ( numbers[4] + numbers[5] );// total value of products in inventory

        int[] productNum = new int[2];
        productNum[0] = 5211;// hammer part #
        productNum[1] = 5212;// shovel part #

        System.out.print(numbers[6]);
    }
    public static float total(){
        return 0;
    }        
}

1 个答案:

答案 0 :(得分:-1)

如果您只想让总方法添加两个元素,请将其更改为:

public static float total(float x, float y)
{
    return x + y;
}

你可以这样称呼

numbers[6] = total(numbers[4], numbers[5]);