我找到了一个程序示例,它转换输入并根据值打印它。但我注意到,如果我添加更大的值,我会收到错误
integer number too large: 9394343298
有什么方法可以解决这个问题吗?
String readableFileSize = readableFileSize(939343298);
System.out.println("Result " + readableFileSize);
public static String readableFileSize(long size)
{
if (size <= 0)
return "0";
final String[] units = new String[] {"B", "kB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
答案 0 :(得分:1)
只需在数字末尾添加L
即可将其标记为长值:
String readableFileSize = readableFileSize(9394343298L);
答案 1 :(得分:0)
问题在于,如果使用常量值,则默认值为整数,但整数最大值为2147483647,其为&lt; 9394343298.所以 出现编译错误:
Main.java:15: error: integer number too large: 9394343298
String readableFileSize = readableFileSize(9394343298);
因此,要么在常量值之后使用'L'将值标记为long,要么使用将赋予函数的long变量。
像这样:
long value = 9394343298L;
String readableFileSize = readableFileSize(value);
参见示例:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String readableFileSize = readableFileSize(9394343298L);
System.out.println("Result " + readableFileSize);
}
public static String readableFileSize(long size)
{
if (size <= 0)
return "0";
final String[] units = new String[]
{
"B", "kB", "MB", "GB", "TB"
};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
工作示例: