2016-02-25 66 views
0

问题:调试Java程序 - 字节转换器

收件通过转换它的字节为更人类可读的格式的一个给定的号码转换成以下之一的程序:字节,千字节,兆字节,千兆字节,或太字节。例如,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

(错误):异常在线程 “主” java.lang.ArithmeticException:/由零 在ByteConverter.main(ByteConverter.java:23

+2

做什么你认为'(long).1099511627776'的价值是? – resueman

回答

2

使用小数点是不是有帮助的转换2 成long。实际上,你已经提供的double文字,.1099511627776,小于1,且将其投射到long,这将产生0

注意去掉小数点是不够的,因为1099511627776不是有效int文字;该值太大。

使用L后缀指定long文字。

1099511627776L 

或者,移位1L剩下40个位置。

1L << 40 
0

尝试学习阅读错误消息:

(Error): Exception in thread "main" java.lang.ArithmeticException:/by zero at ByteConverter.main(ByteConverter.java:23 

“23” 指的行号,这样的错误是在第23行,(长)0.1099511627776必须是零