java - 如何创建一个循环来计算一个特定数字可以安装在另一个特定数字中的次数?

标签 java loops if-statement for-loop nested-loops

我正在创建一个程序,它应该像这样工作;首先程序读取 从键盘输入运输工具(例如卡车)的总体积(以立方米为单位)。接下来,程序计算卡车中可以存放多少个袋子, 显示此信息。

我总是想使用尽可能多的大袋子,这意味着我想使用尽可能多的最大的袋子,然后当它们无法再容纳最大的袋子时,我想存储尽可能多的中间袋子尽可能大小的袋子,当他们无法存放中型袋子时,他们会使用最小尺寸的袋子来填充剩余的空间。

这就是我试图解决这个问题的方法,但最大的问题仍然是循环或逻辑部分,我不知道如何循环这些东西以便打印出我想要的内容。

    package volumecalc;

import java.util.*;

public class BagObject {

    Scanner input = new Scanner(System.in);
    //volume in cubic meter
    int sBag = 10 * 10 * 30;     //Size of the smallest bag
    int mBag = 50 * 100 * 40;    //Size of the middle bag
    int bBag = 100 * 200 * 50;   //Size of the biggest bag
    int transVol;

    public void bag() {
        System.out.println("Enter the current volume of your transport: ");
        transVol = input.nextInt();

        if (transVol > bBag) {
            //Probaly here or more places, I need help
        } else if (transVol < sBag) {
            //Probaly here or more places, I need help
        }

    }

}

主类:

    package volumecalc;

import java.util.*;

public class VolumeCalc {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("                THIS PROGRAM WILL CALCULATE THE SPACE (IN cubic centimeter) IN TRANSPORT:\n\n");
        BagObject bo = new BagObject();
        bo.bag();

    }

}

最佳答案

这就是我要做的:

int numbBag, nummBag, numsBag;    
int remainder;

numbBag = transvol / bBag;
remainder = transvol % bBag;

nummBag = remainder / mBag;
remainder %= mBag;

numsBag = remainder / sBag;

假设传输没有特定的形状。

如果您想要一个可重复用于任意数量袋子的环,您可以这样做:

const int NUM_BAGS = 3;
//put all your bag sizes here
int[] bags = {bBag, mBag, sBag, /*other bags*/};//Array of bags from largest to smallest
int[] numBags = new int[NUM_BAGS];//Number of each bag in the transport
int remainder = transVol;

for(int varA; varA < NUM_BAGS; varA++)
{
    numBags[varA] = remainder / bags[varA];
    remainder %= bags[varA];
}

bBags的数量在numBags[0]中,mBags在numBags[1]中等等,按从大到小的顺序排列。

关于java - 如何创建一个循环来计算一个特定数字可以安装在另一个特定数字中的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992510/

相关文章:

r - 循环遍历数据框中的列并根据 R 中的特定条件连接字符串

python - 如何使用Python脚本解决XML标签没有值的情况下的StopIteration问题

java - 使用 Core Java 在 Selenium 中运行混合框架时,访问被拒绝并且只允许本地连接

java - 在 Java 中生成数据驱动的单元测试

php - 在 foreach 循环中声明的 PHP 变量是否在每次迭代时被销毁并重新创建?

javascript - 循环nodejs中的setInterval

php - 警告 : filesize function failing to operate

delphi - 编译器如何处理 case 语句?

Java nio 连接正在创建多个套接字级连接,为什么?

java - 编写 Maven2 站点插件时获取站点资源列表的最佳方法是什么?