2016-02-25 48 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必須是零