数组循环将自身乘以1024

时间:2013-10-11 09:25:00

标签: java loops

我正在尝试创建一个数组,这样无论字节输入如何,接下来的三个答案都将乘以1024.此时输入都是相同的。感激如果有人可以提供帮助

public class ExcerciseFour {
    static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
    final String [] UNITS = {"B","KB","MB","GB"};

    double bytes;
    double kilobytes;
    double megabytes;
    double gigabytes;

    System.out.print("Enter in bytes: ");
    bytes = keyboard.nextDouble();
    kilobytes = (bytes/1024);
    megabytes = (bytes/1048576);
    gigabytes = (bytes/1073741824);

//  System.out.println(bytes+"bytes"+" is equivalent to "+kilobytes+(UNITS[1])+", "+megabytes+UNITS[2]+", "+gigabytes+UNITS[3]+".");

    double [] conversion = new double [3];
    for(int i=0;i<conversion.length;i++){
            conversion[i]=bytes/1024;
        }
        System.out.println(Arrays.toString(conversion));
    }

}

2 个答案:

答案 0 :(得分:0)

它们都是一样的,因为你为它们分配了所有bytes/1024。由于bytes不会改变,因此它们应该都是相同的。

要解决此问题,您可以将辅助变量除以1024并重新分配给自身。

答案 1 :(得分:0)

这样的东西
 val = bytes
 for(int i=0;i<conversion.length;i++)
 {
        conversion[i]=val;
        val /= 1024
 }