尝试制作方法打印



我试图将数字分为两个类别。数字(实际数字)和计数(该数字发生了多少个),所有数字都存储在50个整数的数组中。我使用气泡排序方法按降序排序此数组。

我的打印方法需要工作。代码可以很好地编译,但是当我运行代码时,什么也不会输出。

为什么我的代码不打印任何东西?

这是我的代码

public class HW5{
    public static void main(String[] args) {
        int[] array = new int[50];
        bubbleSort(array, 'D');
        printArray(array);
    }
    public static void bubbleSort(int[] array, char d){
        int r = (d=='D') ? -1 : 1 ;
        for (int f = 0; f < array.length - 1; f ++){ 
            for (int index = 0; index < array.length - 1; index++){    
                if (array[index] > array[index + 1]){       
                }
            }        
        }
    }
    public static void printArray(int[] array){
        int count = 0;
        int i = 0;
        for(i = 0; i < array.length - 1; i++){
            if (array[i]== array[i + 1]){
                count = count + 1;
            }else{
                System.out.printf(count + "/t" + array[i]);
                count = 0;
            }   
        }
    }                   
}

为什么我的代码不打印任何东西?

对象 array 持有50个元素,所有这些元素都设置为零, printArray 方法在且仅当此条件为false

时才会打印。
array[i] != array[i + 1]

,但是由于数组中的所有元素都是0 ...您只是不打印任何东西...

您的代码正在打印任何内容,因为您没有将数组值设置为任何东西。因为您没有将数组设置为任何内容,所以Java默认所有值都为0。如果array[i] == array[i+1]我会将您的打印方法更改为:

public static void printArray(int[] array){
    int count = 0;
    int i = 0;
    for(i = 0; i < array.length - 1; i++){
        if (array[i]== array[i + 1]){
            count = count + 1;
        }else{
            System.out.print(count);
            count = 0;
        }
        System.out.print(array[i]); //Moved this line out of the if/else statement so it will always print the array at i   
    }
}

我只更改了我评论的行。但是,如果您确实更改了数组的值,则原始代码将起作用。对于随机值,首先您需要导入java.util.Math,然后执行以下操作:

for(int i = 0; i < array.length; i++)
    array[i] = (int)Math.random() * 100; //Sets the array at i to a random number between 0 and 100 (non-inclusive)

这将帮助您的代码根据需要工作。希望这会有所帮助!

编辑:修复语法错误。

最新更新