方法中的数组元素并将值返回给数组
Array elements in methods and returning value back to array
我正在为产品(无特定项目)程序编写一些代码。以下是我需要帮助学习的内容:
我需要取两个数组元素(numbers[4] 和 numbers[5]),创建一个方法,在该方法中将它们相加,然后 return 并将它们存储回数组元素 numbers[ 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;
}
}
如果您只想将两个元素相加,则将其更改为:
public static float total(float x, float y)
{
return x + y;
}
你可以这样称呼它
numbers[6] = total(numbers[4], numbers[5]);
我正在为产品(无特定项目)程序编写一些代码。以下是我需要帮助学习的内容:
我需要取两个数组元素(numbers[4] 和 numbers[5]),创建一个方法,在该方法中将它们相加,然后 return 并将它们存储回数组元素 numbers[ 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;
}
}
如果您只想将两个元素相加,则将其更改为:
public static float total(float x, float y)
{
return x + y;
}
你可以这样称呼它
numbers[6] = total(numbers[4], numbers[5]);