通过范围限制“过滤”值并使用所述值从二维数组中检索值?

问题描述 投票:0回答:1

抱歉标题令人困惑。明确地说,我正在尝试:

  1. 获取用户输入(例如:x = 10)
  2. 通过范围限制“过滤”输入(例如:{0, 5, 11, 16, 20})
  3. 根据数组的“深度”将 while 循环控制变量分配给 x(例如:循环三次,因为 'x' 大于 5 但不大于 11,因此 x = 3)
  4. 使用该值检索 2D 数组值(例如:定价[0][x] = 1)

问题也出现了......它没有按预期工作。无论我输入什么数量,程序都只输出“1”。下面是我使用的代码。缺少的东西我可以提供

//Main.java
    public static void orderMenu(Orders ord) {
        Scanner uIn = new Scanner(System.in);
        int sAmt = 0;
        int mAmt = 0;
        int lAmt = 0;
        int x = 0;
        //Placeholder Function until I can think of something better
        while(x != 4){
            x = uIn.nextInt();
            System.out.print("Enter amount desired: ");
            if(x == 4){
                break;
            }
            //This function will stack on the amounts the user enters
            switch(x){
                case 1:
                    sAmt += uIn.nextInt();
                    break;
                case 2:
                    mAmt += uIn.nextInt();
                    break;
                case 3:
                    lAmt += uIn.nextInt();
                    break;
            }
            //Prints the list out again
            System.out.print(pList); //I removed this from the snip since it is gargantuan
        }
        //Calls Orders.java and calculates prices
        ord.setSmall(sAmt);
        ord.setMed(mAmt);
        ord.setLarge(lAmt);
        System.out.println(ord.reciept()); //Displays calculated price. Only smallPrice for now
    }

//Calc.java code
    public String receipt(){
        calculations();
        String receipt = "\nDebug Price:" + smallPrice;
        return receipt;
    }

    public void calculations(){
        int[] rangeLim = {0, 5, 11, 16, 20}; //limits array
        int[][] pricing = {{1, 2, 3, 4, 5},     //Row 1
                           {3, 6, 9, 12, 15},   //Row 2
                           {5, 10, 15, 20, 25}};//Row 3
        int sub = rangeLim.length - 1;
        
//This is where I am having trouble:

        //finds the y for pricing[x][y]
        while(sub >= 0){
            //System.out.print(sub);
            if(smallOrder >= rangeLim[sub]){
                smallOrder = rangeLim[sub];
            }
            if(mediumOrder >= rangeLim[sub]){
                mediumOrder= rangeLim[sub];
            }
            if(largeOrder >= rangeLim[sub]){
                largeOrder = rangeLim[sub];
            }
            --sub;
        }
        
        //Assigns price value to variable
        smallPrice = pricing[0][smallOrder];
        mediumPrice = pricing[1][mediumOrder];
        largePrice = pricing[2][largeOrder];
    }

我不确定我应该包含多少或多少,但我希望这已经足够了。

为了明确我的目标:如果输入1,它将等待接收“sAmt”的输入。输入“16”等值后,它将再次循环。输入 4 将结束循环,我应该看到“4”或定价[0][3]

我有点迷失在这里。

java arrays if-statement multidimensional-array while-loop
1个回答
0
投票

为此,我想我有一个解决方案,它需要以不同的方式设置另一个数组,但我不想给你任何不起作用的东西。我可以向您展示我的想法,但我宁愿查看 ord 对象,以便在将其发布到此处之前验证它是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.