我是一个java初学者,我正在编写一个程序来获取商品的名称、商品的单位、价格/单位和总价。我正在尝试将这些值放在不同的数组中,以便稍后在创建某种收据时访问它们,但我不知道如何在数组位置分配这些值,然后访问这些相同的位置而无需硬编码. 循环是最好的选择,但我不知道如何设置这个东西。帮助和建议将不胜感激。请记住,我不能做高级的东西,比如矩阵和 3D 数组。如果你能保持简单,那就太棒了。
这是主类,我有一个带有 main() 的测试器类,它运行 userInput() 和 menu() 但没有意义,因为它只有 2 行代码。
import java.util.Scanner;
public class GroceryList {
// instance variables
Scanner Price, Items, NumItems, Units;
private double myGross, myNet;
private final double STATETAX;
private double totalPrice, unitPrice;
private String itemName;
private int totalUnits;
///////////////////////////////////////////// arrays I will use
private double[] totalPrice1;
private double[] unitPrice1;
private String[] itemName1;
private int[] totalUnits1;
public GroceryList()
{
STATETAX = 0.06;
double[] totalPrice = new double[50];
double[] unitPrice = new double[50];
String[] itemName = new String[50];
int[] totalUnits = new int[50];
}
public void userInput()
{
Scanner Price = new Scanner(System.in);
Scanner Items = new Scanner(System.in);
Scanner Units = new Scanner(System.in);
Scanner NumItems = new Scanner(System.in);
int u, c, totalItems;// c is the number of items that has to equal totalItems in order for the loop to break
double price;
String item;//gets the name of the item
c=0;
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
do
{
c++ ;
System.out.print("Enter the item name : ");
item = Items.nextLine();
System.out.print("Enter the units of " + item + " you want to buy : ");
u = Units.nextInt();
System.out.print("Enter the price of a/n " + item + " : $");
price = Price. nextDouble();
/*this would make only one value appear at the receipt, which would be only one item name, one unit price, one price/unit, one total price and the other values calculated
would not appear on the receipt because you cant assign more than 1 value to a variable so thats why I need arrays.
*/
itemName = item;
totalUnits = u;
unitPrice = price;
calc(u,price,item);
}
while (c < totalItems);
}
public void calc(int u, double p, String i)
{
double total;//total amount of $ for 1 item
total = u*p;
System.out.println("Total price of " + i + " : $" + total + "\n");
grossPay(total);
totalPrice = total;
}
public void grossPay(double total)
{
double gross;
myGross += total;
}
public double tax()
{
double temp;
temp = myGross*STATETAX;
myNet = myGross - temp;
return myNet;
}
public void menu()
{
System.out.printf("%-10s %6s %11s %11s" , "ITEM :" , "UNITS :" , "PRICE :" , "TOTAL :");
System.out.println();
System.out.printf("%-11s %2d %7s $%4.2f %5s $%2.2f", itemName, totalUnits,"", unitPrice,"", totalPrice);
System.out.println();
}
public void payment()
{
System.out.println("Amount before tax : $" + myGross);
System.out.println("Amount after tax : $" + tax());
}
}//end GroceryList