【问题标题】:Debugging a Java program - Byte Converter调试 Java 程序 - 字节转换器
【发布时间】: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的价值是多少?

标签: java debugging


【解决方案1】:

使用小数点对于将 240 转换为 long 没有帮助。您实际上提供了一个小于 1 的 double 文字 .1099511627776,并且您将其转换为 long,从而产生 0

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

使用L 后缀指定long 文字。

1099511627776L

或者,将 1L 左移 40 个位置。

1L << 40

【讨论】:

    【解决方案2】:

    尝试学习阅读错误信息:

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

    "23" 表示行号,因此错误在第 23 行,(long).1099511627776 必须为零

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 2015-09-16
      相关资源
      最近更新 更多