【发布时间】:2016-02-25 16:38:10
【问题描述】:
问题:
编写一个程序,将给定数量的字节转换为更易于阅读的格式,方法是将其转换为以下格式之一:字节、千字节、兆字节、千兆字节或太字节。例如,1024 字节为 1.00 KB(KB = 千字节)。
以下是我一直在尝试调试的代码,但到目前为止还没有成功。鉴于下面的错误消息,我不知道在哪里除以零。
import java.text.DecimalFormat;
import java.util.Scanner;
class ByteConverter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan1 = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
long input1;
long conversionKilobyte;
long conversionMegabyte;
long conversionGigabyte;
long conversionTerabyte;
System.out.print("Enter number of bytes: ");
input1 = scan1.nextLong();
conversionKilobyte = input1 / 1024;
conversionMegabyte = input1 / 1048576;
conversionGigabyte = input1 / 1073741824;
conversionTerabyte = input1 / (long).1099511627776;
if (input1 > (long).1099511627775) {
System.out.println(input1 + " " + "Bytes is" + " " + conversionTerabyte + " " + "TB");
} else if (input1 >= 1073741824 && input1 <= (long).1099511627776) {
System.out.println(input1 + " " + "Bytes is" + " " + conversionGigabyte + " " + "GB");
} else if (input1 >= 1048576 && input1 <= 1073741823) {
System.out.println(input1 + " " + "Bytes is" + " " + conversionMegabyte + " " + "MB");
} else if (input1 >= 1024 && input1 <= 1048575) {
System.out.println(input1 + " " + "Bytes is" + " " + conversionKilobyte + " " + "KB");
} else {
System.out.println(input1 + " " + "Bytes is" + " " + df.format(input1) + " " + "B");
}
}
}
这是我收到的输入和错误消息。感谢您的帮助,谢谢!
(输入):输入字节数:5
(错误):线程“main”中的异常 java.lang.ArithmeticException:/ 为零 在 ByteConverter.main(ByteConverter.java:23
【问题讨论】:
-
你觉得
(long).1099511627776的价值是多少?