簡體   English   中英

如何在此Java代碼中使用數組,以便我可以按順序輸出將它們分配給位置的值?

[英]How to use arrays in this java code so I can output values in order they are assigned to positions ?

我是一名Java初學者,正在編寫一個程序,該程序獲取商品的名稱,該商品的單位,價格/單位和總價。 我試圖將這些值放在不同的數組中,以便稍后在創建某種收據時可以訪問它們,但是我不知道如何在數組位置分配這些值,然后訪問這些相同的位置而不必進行硬編碼。 循環是最好的選擇,但我不知道該如何設置。 幫助和建議將不勝感激。 請記住,我不能做矩陣和3D數組之類的高級內容。 如果您可以保持簡單,那就太好了。

這是主要類,我有一個帶有main()的測試器類,該類運行userInput()和menu(),但沒有意義,因為它只有兩行代碼。

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

讓我們開始進行一些重組;)

首先,您真的不需要數組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

看一下這個例子的一些想法;)

理想情況下,您會(寫這是因為我誤解了您的排序含義):

創建一個對象Item ,其字段name totalPriceunitPricetotalUnits 然后,在您的購物清單中,您不必有4個數組,而只需一個Items數組。 節省了必須跟蹤索引的可疑任務。

如果您還創建一個實現ComparatorItemComparator類,則可以定義如何對它們進行排序,然后可以使用以下方法對數組進行排序

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

您也不需要四個掃描儀,因為它們都位於System.in上,所以您可以使用同一台掃描儀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM