2012-10-01 40 views
0

我需要编写一个程序,使用气泡排序方法和主要功能,要求用户输入他们的数组。之后,程序按升序对数组进行排序。我的程序现在要求用户输入,但是一旦发生这种情况,程序将无法编译,我被卡住了。下面的代码:按升序排列的气泡 - 程序无法编译

import java.util.Scanner; 
public class IntSorter{ 
    public static int bubbleSort(int[] a){ 
    boolean needNextPass =true; 
    for(int i=1; i<a.length && needNextPass; i++){ 
     needNextPass = false; 
     for(int j=0; j<a.length - i; j++){ 
     if(a[j]> a[j+1]){ 
      int temp = a[j]; 
      a[j]=a[j+1]; 
      a[j+1] = temp; 
      needNextPass = true; 
      } 
     } 
     } 
    for(int i=0; i<a.length; i++){ 
    System.out.print(a[j] + " "); 
    } 
    } 
public static void main(String[] args){ 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter size of array: "); 
    int N = input.nextInt(); 
    int[] x = new int[N]; 
    System.out.print("Enter " +N +"numbers of your array: "); 
    for(int i= 0; i<N; i++){ 
     x[i] = input.nextInt() 
    } 
    IntSorter access = new IntSorter(); 
    System.out.print("Your sorted array is: "); 
    access.IntSorter(x);} 
} 
+1

'但是一旦发生这种情况,程序将不会编译': - 您的程序在您已经运行后不能编译? –

+0

你收到什么信息? – raam86

回答

0

此行似乎缺少一个分号:

x[i] = input.nextInt() 

而且你似乎是进入其范围的变量j外:

System.out.print(a[j] + " "); 
1

你最后在你的主要方法中是: -

access.IntSorter(x); 

替换此符合: -

access.bubbleSort(x); 

并采用single uppercase字符作为变量是可怕..使用size代替数组的大小..

System.out.print("Enter " +N +"numbers of your array: "); 
    for(int i= 0; i<N; i++){ 
     x[i] = input.nextInt() 
    } 

而在上面的代码中,如果用户什么没有输入一个整数值?你会得到一个例外。你需要赶上..

+0

好的,我修复了你指出的所有错误,并且程序正在运行。谢谢 –

+0

@ChaseChensta .. Congrats .. :) ..但是请考虑处理您可能通过用户输入来得到的'exception'.. –

+0

@ChaseChensta ..并且您需要通过单击其上的大箭头来接受其中一个答案每个问题的左侧 –

0

你可以使用i代替j这是不确定的:

for (int i = 0; i < a.length; i++) { 
    System.out.print(a[i] + " "); 
} 

而且

public static int bubbleSort(int[] a) { 

没有int返回值;

您可以使用您的编译器或IDE来帮助突出显示这些问题。