Groovy-java同时进行多个转换

Groovy-java同时进行多个转换,java,variables,groovy,Java,Variables,Groovy,我想知道是否有人有关于如何同时转换KB变量的技巧 Memory RAM total: 5000000 // KB Memory RAM used: 2000000 // KB Memory RAM available: 3000000 //KB 我正在访问一台Linux远程计算机,同时检索3个变量: 它们是:内存RAM总量、已用内存RAM和可用内存RAM。 这些变量是以KB的“格式”接收的,但我需要以GB为单位显示它们(参见下面的示例) 我一次只能转换一个,我的想法是同

我想知道是否有人有关于如何同时转换KB变量的技巧

Memory RAM total: 5000000      // KB
Memory RAM used: 2000000       // KB
Memory RAM available: 3000000  //KB
我正在访问一台Linux远程计算机,同时检索3个变量:

它们是:内存RAM总量、已用内存RAM和可用内存RAM。 这些变量是以KB的“格式”接收的,但我需要以GB为单位显示它们(参见下面的示例)

我一次只能转换一个,我的想法是同时转换它们

Memory RAM total: 5000000      // KB
Memory RAM used: 2000000       // KB
Memory RAM available: 3000000  //KB
这就是我到目前为止只转换内存RAM总变量所做的

def size = 5000000 // Memory that can be converted KB MB GB AND TERABYTE

String hrSize = ""

try {
    int k = size
    double m = size / 1024 // bytes
    double g = size / 1048576 // bytes
    double t = size / 1073741824 // bytes

    DecimalFormat dec = new DecimalFormat("0.00")

    if (k > 1) {
      //If the size is more than 1kb but less than 1024 bytes, the output will be KiloBytes
        hrSize = dec.format(k).concat("KB")
    }
    if (m > 1) {
      //If the size is more than 1kb but less than 1048576 bytes, the output will be Megabytes
        hrSize = dec.format(m).concat("MB")
    }
    if (g > 1) {
      //If the size is more than 1kb and more than 1048576 but less than 1073741824 bytes, the output will be Gigabytes
        hrSize = dec.format(g).concat("GB")
    }
    if (t > 1) {
      //If the size is more than 1073741824 bytes the output will be Terabytes.
        hrSize = dec.format(t).concat("TB")
    }
} catch (Exception e) {
    println("This program ran into a problem, root cause" + e)

}
println(" The total memory from this computer is: " + hrSize)
输出:

The total memory from this computer is: 4,77GB
我在找什么

The total memory from this computer is: 4,77GB
The total free from this computer is: 1,91GB
The total Available from this computer is: 2,86GB

有任何文档或提示吗?

您可以通过使函数成为一个循环来改进该函数。不清楚您在询问什么或当前代码中存在什么问题。将该代码放入函数中,并在该函数上迭代总值/已用值/可用值。如果您在迭代部分遇到问题,请添加您尝试过的内容以及失败的原因,以便我们可以对其进行改进。您好@daggett,我试图尽可能清楚地说明您不能准确理解的内容?谢谢@cfrick的建议