Reputation: 55
Am new in Java, I want to know why i have exceptions even though i got the answers i required. Below is the Source code
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);
}
}
And here is the output
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
Upvotes: 0
Views: 200
Reputation: 14868
The problem is here:
for (i = 1; i <= num.length; i++){
num[i] = input.nextInt();
if (num[i] == 0)
break;
count++;
}
i in your loop takes values between 1 - num.length where num.length = 30.
So at some point, your program tries to execute
num[30] = input.nextInt();
which will result in an error! Cos 30 out of the bound of the array indices. The correct range of index should be between 0 and 29.
Two possible corrections are:
Loop from 0 - (num.length - 1):
for(i = 0; i <= num.length - 1; i++){
num[i] = input.nextInt();
if (num[i] == 0)
break;
count++;
}
Loop from 1 - num.length as before, but update the index of num appropriately:
for(i = 1; i <= num.length1; i++){
int index = i - 1;
num[index] = input.nextInt();
if (num[index] == 0)
break;
count++;
}
Upvotes: 1
Reputation: 2365
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);
Should be:
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);
Upvotes: 1