首页 > 解决方案 > 如何在循环中堆叠计算结果

问题描述

所以我在每次代码循环时试图弄清楚如何堆叠我的计算时遇到了一些麻烦。

import java.util.Scanner;        

public class packaging {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    double l = 0;
    double w = 0;
    double h = 0;

    Scanner in = new Scanner(System.in);

    System.out.println("Enter the Lenght");
    l = in.nextDouble();
    System.out.println("Enter the Lenght");
    w = in.nextDouble();
    System.out.println("Enter the Lenght");
    h = in.nextDouble();



    while (l>=5 && w>=5 && h>=5) {

        surfaceArea = 2*(l*w + w*h + l*h);
        boxCount = boxCount + 1;

    }

}        

每次while循环循环时,我都试图显示每个结果。如果我输入长度 120 宽度 60 和高度 40,我希望每次从原始输入的数字中减去长度、宽度和高度时打印出结果,这意味着数字将变为 110 50 和 30,但我仍然希望得到结果退出循环并打印。有谁知道我会怎么做?

标签: javaloopswhile-loopoperators

解决方案


假设你想要的就是我认为你想要的,

import java.util.Scanner;

public class packaging {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    double l = 0;
    double w = 0;
    double h = 0;
    double boxCount = 0;
    double surfaceArea = 0;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the Lenght");
    l = in.nextDouble();
    System.out.println("Enter the Lenght");
    w = in.nextDouble();
    System.out.println("Enter the Lenght");
    h = in.nextDouble();



    while (l>=5 && w>=5 && h>=5) {

        surfaceArea = 2*(l*w + w*h + l*h);

        boxCount = boxCount + 1;
        l = l - 10;
        w = w - 10;
        h = h - 10;

        System.out.println("The box count is "+ boxCount);
        System.out.println("The surface Area is "+ surfaceArea);
    }
    in.close();
}

样本输出

Enter Length
15
Enter Length
20
Enter Length
30
The Box count is 1
The Surface Area is [CALCULATED_VALUE]
The Box count is 2
The Surface Area is [CALCULATED_VALUE]
The Box count is 3
The Surface Area is [CALCULATED_VALUE]

这将在每次循环运行时打印 boxCount 和 surfaceArea。希望这是您想要的,如果不是,请添加更多信息,我很乐意提供帮助。


推荐阅读