gpt4 book ai didi

java - ArrayIndexOutOfBoundsException : -1 in recursive sorting

转载 作者:行者123 更新时间:2023-12-02 07:08:15 27 4
gpt4 key购买 nike

我是 Java 新手,我想知道为什么我有异常,即使我得到了我需要的答案。下面是源代码

package habeeb;

import java.util.*;

public class Habeeb
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count = 0;
System.out.println("Enter the integers between 1 and 100");
for (i = 1; i <= num.length; i++)
{
num[i] = input.nextInt();
if (num[i] == 0)
break;
count++;
}
Sorting(num, i, count);
}

public static void Sorting(int[] sort, int a, int con)
{
int j, count = 0;
for (j = 1; j <= con; j++)
{
if (sort[a] == sort[j])
count++;
}
System.out.println(sort[a] + " occurs " + count + " times");
Sorting(sort, a - 1, con);
}
}

这是输出

run:
Enter the integers between 1 and 100
1
2
3
2
2
4
5
3
6
1
0
0 occurs 0 times
1 occurs 2 times
6 occurs 1 times
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
3 occurs 2 times
5 occurs 1 times
4 occurs 1 times
2 occurs 3 times
2 occurs 3 times
3 occurs 2 times
2 occurs 3 times
1 occurs 2 times
0 occurs 0 times
at habeeb.Habeeb.Sorting(Habeeb.java:18)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.Sorting(Habeeb.java:21)
at habeeb.Habeeb.main(Habeeb.java:14)
Java Result: 1

最佳答案

public static void Sorting(int[] sort, int a, int con){
int j, count=0;
for(j=1; j<=con; j++){
if(sort[a]==sort[j])
count++;
}System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);

应该是:

public static void Sorting(int[] sort, int a, int con){
if(a<0)return;
int j, count=0;
for(j=1; j<=con; j++){
if(sort[a]==sort[j])
count++;
}System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);

关于java - ArrayIndexOutOfBoundsException : -1 in recursive sorting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com