通过范围限制“过滤”一个值,并使用该值从二维数组中检索一个值?

"Filtering" a value through range limits and retrieving a value form a 2D array using said value?

提问人:Takeshi DBXV 提问时间:6/29/2023 更新时间:8/19/2023 访问量:18

问:

对不起,标题令人困惑。需要明确的是,我正在尝试:

  1. 获取用户输入(例如:x = 10)
  2. 通过范围限制“过滤”输入(例如:{0, 5, 11, 16, 20})
  3. 根据 while 循环控制变量在数组中的“深度”程度将 while 循环控制变量分配给 x(例如:循环三次,因为 'x' 大于 5 而不是 11,所以 x = 3)
  4. 使用该值检索 2D 数组值(例如:pricing[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 if-statement 多维数组 while-loop

评论


答: 暂无答案