排序后用Java打印数组列表的错误
我正在做一个项目,该项目包括基于数字输入创建一个数组,然后通过输入分配int值。然后,它运行一个冒泡排序,按递增顺序对值进行排序。我在印刷上遇到了麻烦。我使用Eclipse作为我的IDE,我不能真正理解我做错了什么。任何帮助都将不胜感激 导入java.util.Scanner排序后用Java打印数组列表的错误,java,Java,我正在做一个项目,该项目包括基于数字输入创建一个数组,然后通过输入分配int值。然后,它运行一个冒泡排序,按递增顺序对值进行排序。我在印刷上遇到了麻烦。我使用Eclipse作为我的IDE,我不能真正理解我做错了什么。任何帮助都将不胜感激 导入java.util.Scanner public class Ex07_18 { public static void main(String[] args) { Scanner input = new Scanner(System
public class Ex07_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt user to enter the numbers of integers to be entered
System.out.print("Enter the number of integers:");
final int NUM_OF_INTS = input.nextInt();
int[] numbers = new int[NUM_OF_INTS];
// Input the numbers into an array
for (int i = 0; i < NUM_OF_INTS; i++) {
System.out.print("Enter an integer: ");
numbers[i] = input.nextInt();
}// end for
// Bubble sort the array
bubbleSort(numbers);
// Print out the integers
printList(numbers);
input.close();
}// end main
public static void bubbleSort(int[] list) {
int listLength = list.length;
int temp;
boolean is_sorted;
for (int i= 0; i < listLength; i++) {
is_sorted = true;
for (int j = 1; j < listLength; j++) {
if (list[j - 1] > list[j]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
is_sorted = false;
} // end if
} // end for
if (is_sorted) break;
} // end for
}// end bubbleSort
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++ ) {
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList
}// end Ex07_18
公共类Ex07\u 18{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
//提示用户输入要输入的整数数
System.out.print(“输入整数的数目:”);
final int NUM_OF_INTS=input.nextInt();
int[]numbers=新的int[NUM_OF_INTS];
//将数字输入一个数组
for(int i=0;i列表[j]){
温度=列表[j-1];
列表[j-1]=列表[j];
列表[j]=温度;
is_sorted=false;
}//如果结束,则结束
}//结束
如果(已排序)中断;
}//结束
}//端部气泡运动
公共静态无效打印列表(int[]编号){
对于(int i=0;i
在打印列表方法中的for循环中,您可以迭代number.length-1元素,而不是number.length元素。您的printList方法应如下所示:
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length; ++i ) {
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList
公共静态无效打印列表(int[]编号){
对于(int i=0;i
在printList函数中,您设置的比较条件不正确
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++ ) { //should be i <= numbers.length - 1
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList
公共静态无效打印列表(int[]编号){
对于(inti=0;ii
更改为i
中的printList