Java 正在尝试使方法打印
我试图把数字分为两类。Number(实际数字)和count(此数字出现的次数),所有数字都存储在50个整数的数组中。我使用冒泡排序方法按降序对该数组进行排序 我的打印方法需要改进。代码编译得很好,但是当我运行代码时,没有输出任何内容 为什么我的代码没有打印任何东西 这是我的密码Java 正在尝试使方法打印,java,Java,我试图把数字分为两类。Number(实际数字)和count(此数字出现的次数),所有数字都存储在50个整数的数组中。我使用冒泡排序方法按降序对该数组进行排序 我的打印方法需要改进。代码编译得很好,但是当我运行代码时,没有输出任何内容 为什么我的代码没有打印任何东西 这是我的密码 public class HW5{ public static void main(String[] args) { int[] array = new int[50]; bubb
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;
}
}
}
}
公共类HW5{
公共静态void main(字符串[]args){
int[]数组=新的int[50];
bubbleSort(数组'D');
打印阵列(数组);
}
公共静态void bubbleSort(int[]数组,字符d){
int r=(d='d')?-1:1;
对于(intf=0;f数组[index+1]){
}
}
}
}
公共静态void打印数组(int[]数组){
整数计数=0;
int i=0;
对于(i=0;i
为什么我的代码没有打印任何东西
对象array包含50个元素,所有元素的值都设置为零,printary方法将在且仅当此条件为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
}
}
这将帮助上面的代码按照您的需要工作。希望这有帮助
编辑:修复了语法错误。数组已初始化,所有元素均为
0
。用于打印的代码从未发现任何不相等的值,因此else
从未执行。
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)