请帮助我在 Java 中实现以下计数排序。我是 Java 和调试新手,所以我不确定错误。下面代码的问题是虽然它编译了,但我没有在屏幕上得到任何输出。请仔细阅读代码并给我一些建议。也许有一些逻辑错误。谢谢
import java.io.*;
import java.lang.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Cnt {
public static void main(String[] args) throws java.lang.Exception {
BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
int[] a ;
int[] b;
String inp = R.readLine();
int N = Integer.parseInt(inp);
a = new int[N];
b = new int[N];
for ( int i = 0; i< N; i++) {
a[i] = Integer.parseInt(R.readLine());
}
int key = findmax(a);
int k = key+1;
int c[] = new int[k];
for ( int i = 0; i < k; i++) {
c[i] = 0;
}
for ( int j = 0; j < a.length; j++){
c[a[j]] = c[a[j]] +1;
}
for ( int i = 1; i < key ; i++) {
c[i] = c[i] + c[i-1];
}
for ( int j = (a.length - 1); j >=0; j--) {
b[c[a[j]]] = a[j];
c[a[j]]= c[a[j]] -1;
}
//System.out.println(b[0]);
for ( int h = 0; h > b.length; h++) {
System.out.println(b[h]);
}
}
private static int findmax(int a[])
{
int r;
r = a[0];
for ( int i =0; i < a.length; i++ ) {
if (a[i] >= r) {
r = a[i];
}
}
return r;
}
}
最佳答案
I am getting an ArrayOutofBoundsException. Please go through the code and suggest me something.
这是错误的做法。你要做的是:
查看异常的堆栈跟踪(您的 IDE 会显示给您)
查看代码中堆栈跟踪显示抛出异常的行
阅读错误消息以找出索引值是什么
通过阅读前面的代码找出该索引值是如何产生的
如果您无法从阅读代码中弄清楚,请使用 IDE 的调试器单步执行程序并观察变量/对象的值是什么以及它们如何变化.
如果您发布异常堆栈跟踪,我们可能会为您解决。事实上,如果有人愿意花一些时间,他们可能可以在没有堆栈跟踪的情况下弄明白。
但这违背了为您提供学习练习的目的。你需要自己学习如何做这类事情......通过自己做。
你问题的原始版本是这样说的:
As per my IDE, I am getting an ArrayOutofBoundsException
我假设因为您的 IDE 告诉您您遇到异常,所以它也会显示异常消息,以及(如果您单击它或其他东西)异常堆栈跟踪。当然,我的 IDE 能够做到这一点。
如果不是这种情况,简单的替代方法是像这样在 main
的整个主体周围放置一个 try/catch block 。
public static void main(String[] args) throws Exception {
try {
// existing main body
...
} catch (Exception ex) {
ex.printStackTrace();
throw ex; // or leave this out.
}
}
关于java - Java中的计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8860219/