【问题标题】:How to use arrays in this java code so I can output values in order they are assigned to positions ?如何在这个 java 代码中使用数组,以便我可以输出值以便将它们分配给位置?
【发布时间】:2013-10-16 02:00:57
【问题描述】:

我是一名 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

【问题讨论】:

  • 您的某些 cmets 难以阅读。考虑将它们分成更多行。

标签: java arrays loops formatting


【解决方案1】:

让我们从一点重组开始;)

首先,你真的不需要数组totalPrice1,总价就是总价,只有一个……(恕我直言)

您应该在userInput 方法中初始化它们,而不是在构造函数中初始化数组,这是当您知道用户想要输入多少项时。否则如果我要输入 51 项,你会遇到问题;)

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();

unitPrice1 = new double[totalItems];
itemName1 = new String[totalItems];
totalUnits1 = new int[totalItems];

(nb-您的原始代码中有错误,在构造函数中,您已将数组声明为局部变量,但无论如何使用了错误的名称,这将使实例字段未初始化,引发NullPointerException)

虽然这肯定不是错误,但在循环结束时增加 c 会更简单...

do {
    //...
    calc(u, price, item);
    c++;
} while (c < totalItems);

这意味着您不需要不断调整数组的位置。

在您的“收集”循环中,您需要将用户输入的值分配给每个数组...

do {
    //...
    itemName1[c] = item;
    totalUnits1[c] = u;
    unitPrice1[c] = price;
    //...
} while (c < totalItems);

说了这么多,实际上使用for-next 循环之类的东西会更容易...

for (int c = 0; c < totalItems; c++) {
    //...
}

恕我直言...

最后,当您准备好后,您可以通过简单地遍历数组来打印收据...

for (int index = 0; index < totalItems; index++) {
    double itemCost = unitPrice1[index] * totalUnits1[index];
    System.out.println(itemName1[index] + " @ " + unitPrice1[index] + " x " + totalUnits1[index] + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);

一些反馈 ;)

说了这么多,我个人会为自己创建一个简单的Object,其中包含所有必需的信息,例如;

public class ShoppingItem {
    public String name;
    public double unitPrice;
    public double quantity;
}

然后,您只需要一个数组,例如...

//private double[] unitPrice1;
//private String[] itemName1;
//private int[] totalUnits1;
private ShopingItem[] items;

然后,根据需要,您只需创建该项目的新实例并填写它,例如...

items[c] = new ShoppingItem();
items[c] = item;
items[c] = u;
items[c] = price;
//itemName1[c] = item;
//totalUnits1[c] = u;
//unitPrice1[c] = price;

打印收据看起来像......

for (ShoppingItem item : items) {
    double itemCost = item.unitPrice * item.quantity;
    System.out.println(item.name + " @ " + item.unitPrice + " x " + item.quantity + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);

对于更“高级”的输出,我建议您查看 String#format 和/或 System.out.printf 之类的内容

看看this example 的一些想法;)

【讨论】:

  • 我正在通过像 GroceryList gc = new GroceryList(); 这样的对象使用另一个类的构造函数然后 gc.userInput();所以我认为这就是你所说的错误。
  • 在您的构造函数中,您创建了double[] totalPrice = new double[50]; double[] unitPrice = new double[50]; String[] itemName = new String[50]; int[] totalUnits = new int[50];。这些都是构造函数本地的,这意味着一旦你退出构造函数,它们就不能再被引用。他们的名字甚至与字段实例都不匹配(private double[] totalPrice1; private double[] unitPrice1; private String[] itemName1; private int[] totalUnits1;),这将使这些未初始化(null)......
  • 是的,基本上我真的必须重建这个东西,因为它已经失控了。感谢您的帮助:)
  • 你正朝着好的方向前进!您可能还会找到一些帮助的Arrays..
【解决方案2】:

理想情况下你会(写这个是因为我误解了你的排序意思):

创建一个对象Item,其中包含字段nametotalPriceunitPricetotalUnits。然后在您的购物清单中,您不需要有 4 个数组,只需一个数组 Items。省去了必须跟踪索引的可疑任务。

如果您还创建了一个实现 ComparatorItemComparator 类,您可以定义它们的排序方式,然后您可以使用对数组进行排序

Collections.sort(Arrays.asList(itemsList), new ItemComparator());

您也不需要四个扫描仪,您可以使用同一个扫描仪,因为它们都在System.in

【讨论】:

  • 谢谢,我会试试这个:)
  • 这将是您第一次习惯使用数组之后的一个很好的步骤,MadProgrammer给出的答案首先更合适。
  • 数组很有趣,Lists 更简单 ;)
猜你喜欢
  • 1970-01-01
  • 2018-12-26
  • 2021-07-25
  • 2021-05-29
  • 2015-03-23
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多