【发布时间】:2021-06-14 10:59:22
【问题描述】:
我正在尝试从一个字符串对象访问每个元素并将其与另一个字符串连接:
当前输出:来自对象 -> hrsize
4,77GB
1,91GB
2,86GB
将 KB 转换为 GB 后,我需要为所有输出命名。 变成这样:
TotalMemory: 4,77GB
MemoryAvailable: 1,91GB
MemoryFree: 2,86GB
有了这个输出,我就可以把它转换成一个 Hashmap。 (k , v)
我尝试遍历列表以为每个值分配一个名称,但没有成功。
我会留下完整的代码:
class Example {
static void main(String[] args) {
int A = 5000000 //TotalMemory -> Kb
int B = 2000000 // MemoryAvailable -> Kb
int C = 3000000 // MemoryFree -> Kb
int[] array = [ A, B, C ] // Convert all variables into an Array
for(int i in array) {
def size = i // Converting each element from the object to be converted into MB GB or TB
// Memory can be converted in KB MB GB AND TERABYTE depending on its size
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(hrSize)
}
}
}
我真的希望有人可以帮助我,因为我已经为此苦苦挣扎了好几天。 可能这是非常基本的事情,但我尽力单独解决它;不开心!
【问题讨论】: