簡體   English   中英

如何從數組中獲取價格?

[英]How do I get the price out of an array?

所以我剛剛完成了這個課堂作業。 我們正在使用順序和二進制搜索來詢問客戶他們正在尋找的零件編號。 然后返回是否找到它,如果找到,則返回帶有請求的零件號的價格。 所以有 2 個數組,一個是零件號的整數,另一個是價格的雙數組。 那么在順序和二進制搜索查找零件號之后,我如何獲得該零件號的價格?

public class InventoryData 
{
    Scanner input = new Scanner(System.in);

    int[] partNum = new int [200];
    double[] priceArray = new double[200];
    int partsCount = 0;
    int customerPart;
    int partPrice;
    String inventoryPricing;
    double customerPrice;

    public InventoryData(String File)
    {
        inventoryPricing = "file";
    }

    public void loadArrays()
    {
        try
        {
            Scanner infile = new Scanner(new FileInputStream("file"));
            while(infile.hasNext())
            {
                partNum[partsCount] = infile.nextInt();
                priceArray[partPrice] = infile.nextDouble();
                ++partsCount;
            }
            infile.close();
        } 
        catch (IOException ex)
        {
            //If file has problems, set the count to -1
            partsCount = -1;
            ex.printStackTrace();
        }
    }

    public void seqSearch()
    {
        System.out.println("What part number are you looking for?");
        customerPart = input.nextInt();
        for(int i=0; i < partNum.length; i++){
            if(customerPart == partNum[i])
                System.out.println("Sequential search found part" + customerPart);

        }
    }
    public int binarySearch()
    {
        int first = 0;
        int mid=0;
        int last = partsCount - 1;
        boolean found = false;
        System.out.println("What part number are you looking for?");
        customerPart = input.nextInt();

        while(first <= last && !found)
        {
            mid = (last + first) /2;
            if(partNum[mid] == customerPart)
            {
                found = true;
            }
            else if(partNum[mid] < customerPart)
                first = mid +1;
            else 
                last = mid-1;
        }
        if(!found)
        {
            mid = -1;
        }
        return mid;
    }
        public double getPrice()
        {
            return customerPrice; 
        }
}// end of inventory data class

第一,讓我提出一些建議:如果您正在學習如何開發應用程序,那么可以,如果您正在嘗試推出一些產品,那么請考慮不使用這樣的邏輯,考慮到列表越大,迭代就越困難遍歷所有數組,直到你可能找到一些東西......

回到你的問題::)

你快到了...

在 for 循環中需要獲取數組 price priceArray並獲取索引處的元素..

訣竅隱藏在這里: priceArray[i]

看:

for(int i=0; i < partNum.length; i++){
    if(customerPart == partNum[i]){
        System.out.println("Sequential search found part" + customerPart);
        // here
        System.out.println("and the price is: " + priceArray[i]);
    }
}

所以你會得到與用戶輸入相關的價格值......

暫無
暫無

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

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