Java 方法中的数组元素并将值返回给数组
我正在为一个产品(无特定项目)程序编写一些代码。以下是我需要帮助学习的内容: 我需要取两个数组元素(数字[4]和数字[5]),创建一个方法,在该方法中将它们相加,然后返回并存储回数组元素数字[6] 如何创建一个可以读取已存储在数组中的信息的方法 这是我的密码:Java 方法中的数组元素并将值返回给数组,java,arrays,methods,Java,Arrays,Methods,我正在为一个产品(无特定项目)程序编写一些代码。以下是我需要帮助学习的内容: 我需要取两个数组元素(数字[4]和数字[5]),创建一个方法,在该方法中将它们相加,然后返回并存储回数组元素数字[6] 如何创建一个可以读取已存储在数组中的信息的方法 这是我的密码: // This is an inventory program part 1 "Section 1" public class inventory { public static void main(String[] args)
// 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;
}
}
如果只希望total方法添加这两个元素,请将其更改为:
public static float total(float x, float y)
{
return x + y;
}
你可以这样称呼它
numbers[6] = total(numbers[4], numbers[5]);
问题是什么?我想从数字[6]开始,作为0的值。然后使用方法添加数字[4]和数字[5]。然后返回新值并将其存储到数字[6]。此代码定义为服务器,但不应像这样使用。数组总是一组数据,在你的数组中,2个表示数量,2个表示价格,2个表示总数,等等,这是不好的。在这里,您可以在total()方法中求和,通过传递数值[4]和数值[5],得到两个数值的和。