ArrayIndexOutOfBounds in sorting - java

I've written my sorting problem as follows, but i am getting an ArrayIndexOutOfBounds exception.
which i'm not able to figure it out. plz help.
System.out.println("Enter the total no of digits to sort:- ");
n = Integer.parseInt(br.readLine());
x = new int[n];
System.out.println("Enter the elements:- ");
for(i = 0; i < n; i++)
x[i] = Integer.parseInt(br.readLine());
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(x[j] > x[j+1]) //ascending order
{
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}

Since j goes up to n, j+1 is out of bound. You need to change it to
for(j=0;j<n-1;j++)
Doing so would make sure that x[j+1] is within bounds.

Error is here:
if(x[j] > x[j+1]) {
....
Because j+1 is equal ton
Make this change:
for(j=0;j + 1<n;j++) {
...

Related

How can I sort using two different packages?

I had an assignment for a class where I had to develop a simple number sort program.
My main is supposed to receive the user input and my sort class is supposed to interrupt and spit out the resulting numbers in ascending and descending order. The problem is that my main is taking the input but it's not putting it in order at all and I'm unsure why.
package main;
import sort.Sort;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int arr[] = new int[5];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<5; i++) {
System.out.print("Enter a number: ");
myScanner.nextLine();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
}
package sort;
public class Sort {
public void ascendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void descendingsort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
I know I'm missing something in my Main, because I'm fairly certain I don't need to put anything else into the sort class.
You're code is perfect. You just missed one assignment in your main method.
Instead of myScanner.nextLine(); you should have written arr[i] = myScanner.nextLine();
myScanner.nextLine(); is getting the next line you enter in the console but it isn't saving it anywhere. arr[i] = myScanner.nextLine(); will save the value of the console in the arr array.
Everything else should work after that.
First you are getting user input using myScanner.nextLine() but not storing it. myScanner.nextLine() won't save anything which user enters .
Thus you need to store it in an array and then use it later. So your main method after the changes should be like this.
public static void main(String[] args) {
int arr[] = new int[3];
Scanner myScanner = new Scanner(System.in);
for(int i=0; i<3; i++) {
System.out.print("Enter a number: ");
arr[i] = myScanner.nextInt();
}
Sort sortObj = new Sort();
sortObj.ascendingsort(arr);
}
And your sorting functions are also wrong. There you do some mis-calculations and return / log nothing. Thus you will not see anything in the console if you are not logging or returning anything.
public void descendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
public void ascendingsort(int array[]) {
int n = array.length;
int i, j, temp;
for (i = 0; i < ( n- 1 ); i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (i = 0; i < n; i++){
System.out.println(array[i]);
}
}
I hope this functions will work for your use case of ascending and descending sort.

Zeros are appending to my arrays in Java programm

If I print my array long pair[] , zeros are appending in empty slots. What is wrong? Any help is welcome.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
diff = arr[j] - arr[i];
if (ndiff == diff) {
pair[x] = arr[i];
x++;
pair[x] = arr[j];
x++;
}
}
}
for(i=0;i!=pair.length;i++){
System.out.print(pair[i]+" ");
}
If you want to print only the values you put in pair, your for loop should run only up to the element with index x-1:
for(i=0; i < x; i++){
System.out.print(pair[i]+" ");
}

How to jump over a specific number in a loop

Didn't know how to call my Thread.
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[j] = numbers[j];
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++){
int k = i;
while(thisTuple[k] <= 0){
k++;
}
newTuple[i] = thisTuple[k];
}
this.tuple = newTuple;
}
This is my code snippet to create a new NaturalNumberTuple.
So this is the Array I want to use: int[] tT2 = {1,2,4,-4,5,4,4};
I only want to use natural numbers greater than 0 and my problem isn't to cut out the negative number but it is that my console is giving me this: Tuple(Numbers:1,2,4,5,5,4).
The problem is if I jump over that value which is negative with my while loop to get the higher (k) I will have to pass the same (k) in my for loop which I don't want to because I already got it in my Array. I hope you understand my problem.
Sorry for the bad english..
Edit: Can't use any methods from java itself like System.arrayCopy
You have an error in the first loop. Fixing it makes the second loop much simpler :
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; // changed thisTuple[j] to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++) {
newTuple[i] = thisTuple[i];
}
this.tuple = newTuple;
}
Of course, the second loop can be replaced with a call to System.arrayCopy.
I would change your while loop to an if that simply restarts the for loop. Say from this:
while(thisTuple[k] <= 0){
k++;
}
To something like this:
if (thisTuple[k] <= 0)
continue;
This stops you from adding the same number twice when you encounter a negative or zero number.
This code will solve you issue. The code is checked in the following link Tuple Exampple
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; //Change to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < count; i++){
newTuple[i] = thisTuple[i];
}

If statements in 2D arrays

When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.

Removing and replacing arrays

Basically, I am given an array of numbers and I have to count all the negative numbers.
Then make a new array that contains all of the positive numbers from the previous with the length of the array being firstarray-numberOfNegatives
Here is my code:
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length-1; i++)
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
I am getting the wrong result: negative numbers are replaced with 0s
At first write i < numbers.length; or i <= numbers.length-1; instead of i < numbers.length-1;
And then fix code.
Also note that you can have zeros in your 'numbers' array, so in if() in first for() you should write <=0 instead of <0
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] > 0) numbers2[count] = numbers[i];
count++;
System.out.println(numbers2[count-1]);
}
Firstly: you have an off-by-one error in your first for loop. Walk through some small example arrays in your head or on paper and you'll see.
Secondly: I think you are using your two index counters backwards in the second section. The count is supposed to be used in your new array, and i in your old one.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++) //
{
if (numbers[i] < 0) numberOfNegative++;
}
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) numbers2[count++] = numbers[i]; //
}
numbers = numbers2;
}
Run through a debugger and watch this line...
That -1 is suspicious
for(int i = 0; i < numbers.length-1; i++)
:)
Need to reverse your index variables in the second pass. Also the first loop had a length-1 instead of length. The second loop should go over the full length of the original array not the resulting array.
public void removeNegatives()
{
int numberOfNegative = 0;
for(int i = 0; i < numbers.length; i++)
if (numbers[i] < 0)
numberOfNegative++;
int [] numbers2 = new int[numbers.length-numberOfNegative];
int count = 0;
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] >= 0) {
numbers2[count] = numbers[i];
System.out.println(numbers2[count]);
count++;
}
}
numbers = numbers2;
}
In
for(int i = 0; i < numbers2.length; i++)
{
if (numbers[count] > 0) numbers2[i] = numbers[count];
count++;
System.out.println(numbers2[i]);
}
numbers = numbers2;
}
You are iterating as many times as numbers2 has positions, however, you increase i at every pass (in the for loop) regardless of whether you fund a positive number or not. Your output arrray would therefore have the first numbers2.length positive integers of numbers interleaved with a bunch of 0s!

Categories