为什么在调用排序方法时会出现此异常?
Exception in thread "JavaFX Application Thread"
java.lang.IllegalArgumentException: 1 > 0
jdk:1.8.0 u281
这是学校的作业。我绝对必须递归地解决这个问题,因为它需要使用字母顺序的递归排序方法。
public void sort1() {
ArrayList<String> sortlist = new ArrayList();
for(int i = 0; i < size(); i ++) {
sortlist.add(getInd(i));
}
String[] testData = sortlist.toArray(new String[sortlist.size()]);
sort(testData);
for(String s: testData) {
System.out.println(s);
}
}
/**
* recursive alphabetical sort method
* @param a the array of string values
*/
public void sort(String[] a) {
if (a.length==1) {
System.out.println("list is not long enough");
}
// Copy array from 1..length-1 into new array rest
String rest [] = Arrays.copyOfRange(a, 1, a.length);
// sort rest
sort(rest);
// insert a[0] into rest and store the result in a
insert(a,rest);
}
// insert a[0] into sort and store result in a
private static void insert(String [] a, String [] sorted) {
int i;
String saveFirst = a[0];
// Find index 'i' where such that sorted[i] > a[0]
for (i=0; i < sorted.length; i++) {
if (saveFirst.compareTo(sorted[i])<0) {
break;
}
}
// Copy elements less than a[0] from sorted to a
for (int j=0; j < i; j++) {
a[j] = sorted[j];
}
// insert a[0]
a[i] = saveFirst;
// copy elements greater than a[0] from sorted to a
for (int j=i+1; j < a.length; j++) {
a[j] = sorted[j-1];
}
}
同样的异常也出现在单独类的事件处理程序和开关中:
@Override
public void handle(ActionEvent event)
{
// Get the command from the command textfield.
TextField cmdTextField = (TextField)event.getTarget();
String cmdText = cmdTextField.getText();
// Use a scanner to read the name of the linked list
// method and do a switch on it.
Scanner sc = new Scanner(cmdText);
String cmd = sc.next();
switch(cmd)
{
case "sort":
ll.sort1();
break;
}
}
1条答案
按热度按时间gwo2fgha1#
这个错误是由于
Arrays.copyOfRange
当from
变量大于to
变量。尝试更改:
以下内容: