array index out of bounds exception in a while loop - java

I'm having this interesting ArrayIndexOutofBounds exception.
The code is this:
int m = 0;
while (scan.hasNextInt())
{
intArray[m++] = scan.NextInt();
}
I'm merely scanning a bunch of integers into an array, but I always get an ArrayIndexOutofBounds error. I thought my int m was already initialized to zero?
Thanks

inputString.length() returns the number of characters in the string. it does not necessarily correspond to the number of numbers in your string.You will want to add another condition to your while statement to ensure that m doesn't get larger than intArray.length. Also you probably want to step through the code with a debugger to determine exactly when the array runs out of space.
Since java arrays are fixed size, if you don't know what the size of your input is going to be, you should instead use ArrayList<Integer> to store your input.

Does the array have any elements in it to start off with?
On future iterations of the loop, m is not zero because you increment it inside the loop.

ArrayIndexOutofBounds means your array isn't big enough to hold the number of values you are putting in it. Where are you initializing the array intArray?
If you don't know how many values the scanner has upfront, which I would assume to be the case, you might want to use an ArrayList instead.
Something like this should work..
List<Integer> intArray = new ArrayList<Integer>();
while (scan.hasNextInt())
{
intArray.add(scan.NextInt());
}
If you need the final results in an array rather then an ArrayLIst, you can use
Integer[] newArray = (Integer[])intArray.toArray();

Related

Java Array Odd Sorting Algorythm

I got an algorithm to write that set order of an Arrey but in a specific way.
Find the lowest number of an array
Save it at the start of the new array.
Mark in the origin (starting) array spot which from we found the lowest number (mark by for example change it to maximum int number).
Go back to point 1.
Repeat all to rewrite all numbers in ascending order.
So I got a working code that changes the order, but I can't figure out how to mark the numbers, and thanks to this create a new array.
public static void arrOrder(int[] intArray){
int temp = 0;
for (int i = 0; i <intArray.length; i++) {
for (int j = i+1; j <intArray.length; j++) {
if(intArray[i] >intArray[j]) {
temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
}
}
So I got a working code that changes the order
No, you don't. Even if you figure out how to do the marking thing, the code you pasted changes the order, perhaps, but it doesn't sort anything.
Your code will, for each element (the i loop):
For each element above it, if it is higher, replace stuff. This isn't, at all, what you wanted - what you wanted is to first figure out if the i-th number is the smallest number. If no, do nothing (continue on to the next number, check if that one is lowest), If yes, write it into a new array, and replace it with some placeholder to indicate that you've already done that one - the suggestion is Integer.MAX_VALUE, a fine suggestion.
The 'strategy' you describe involves:
Making a separate new array of the right size.
Maintaining a variable that counts how many numbers have been written into this new array - when you find your next lowest number, you'd write it at that index.
A double-loop construct where the inner loop doesn't write anything, it merely tracks if the i number is the lowest.
Some code inside the i loop but after the j loop that acts only if i was, in fact, the lowest number. Presumably involves a boolean that you set initially and clear in the inner loop (the j loop), then an if that only acts if the boolean remains true, i.e. - no lower number exists.
The j loop needs to hit the entire array, not 'only stuff above you'.
You need to explicitly exclude your sentinel value. I suggest you use Integer.MAX_VALUE. This probably involves another if.
If you code looks anything like what you pasted, you didn't do it right, given that what you pasted doesn't do any of the named strategy elements.

How to make zeros for next n-1 elements of n similar elements in an array?

I have an integer 667778 and I need to output it as 607008.
I used an array 6,6,7,7,7,8 and xor next similar elements.
I need to this in constant time.
suppose
int arr[]={6,6,7,7,7,8}
int ele=arr[0];
for (int i=1;i<arr.length;i++)
{
if(arr[i]==ele)
arr[i]=0;
else
ele=arr[i];
}
output array arr has [6,0,7,0,0,8]
It is taking O(n) n is size of the array
How can i do this in constant time?
Unless the number given will always be 6 digits (in which case you can hard code it, which is technically constant time, but will give equal performance to the loop), then you can't get constant time because the basis of the problem requires looping through the array in the first place.
Is there are reason you want it to work in constant time anyways, as O(n) is the fastest a program can read the data anyways.
Edit:
After reading your comments, I think you need to come up with a different approach so calculating the XORs won't be inside the loop. I can't provide much more help without the original problem.

Populate an array with unlimited index - Java

Is there a way to populate an array with unlimited indexes in java? I just want the program to keep appending to the array without any capacity.
I declared like this:
int arrInt[] = new int[]
But it says that it is missing dimension. So how can I do it?
Array in Java is static, ie. you have to declare its size while initializing. Hence the answer is 'no' and you are getting the correct message as you have not mentioned the dimension.
No, there isn't.
ArrayList serves that purpose (i.e. an array based list whose capacity increases over time automatically when adding elements to it).
Is there a way to populate an array with unlimited indexes in java?
NO
I just want the program to keep appending to the array without any
capacity.
Need to Use ArrayList
List<Object> arr = new ArrayList<Object>();
arr.add(obj1);
arr.add(obj2);
arr.add(obj3); .. so on
I declared like this - int arrInt[] = new int[]. But it says that it
is missing dimension.
Arrays will always complain to declare the size.
In java, arrays have a maximum number of elements equal to Integer.MAX_VALUE - 5. To get around this, try using a LinkedList which has an unimited number of elements. Since this is a list, you can modify the size whenever necessary in your code. Note that ArrayList also has a max number of elements of Integer.MAX_VALUE, so LinkedList is necessary if you truly need a list of unlimited size.
Resource: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Define the number of elements of a one-dimensional array based on a variable rather than a constant

I am little confused at to what based on a variable means. I made an attempt at it not sure if its correct. Is it?
int size;
System.out.print("Enter the array size: ");
size = input.nextInt();
int[] arr = new int[size];
Define the number of elements of a one-dimensional array based on a
variable rather than a constant
You have done it right. lets break up it into parts to clear your confusion.
Define the number of elements of a one-dimensional array
int size;
System.out.print(“Enter the array size: “);
size = input.nextInt();
here you have defined how many elements should be in you array. In simple words size of array.
based on a variable rather than a constant
you have taken above variable size to define the size of length , it is variable means it can have any value which user enters not hard coded in the code.
Hope your confusion is clear.
Well tried mate.
I think it is not the problem of variable or constant, it is about the confusion of usingnew int[size].
In fact, it is just a second format ofnew int[](size), it will new an object which is an array type. And int is just a generic parameter.

Replacing two characters with one character in a char array

How to replace two characters with one character in a char array? Let me explain a bit more. I have a char array of length n . In this char array i want to replace two characters with one character in a specified index i. In this process the array length is going to decrease by 1.
The idea which i came to my mind is, first create a new char array of length n-1 then copy all elements from index 0 to index i (i excluding) then insert desired character at index i then copy elements from index i+2 (i including) to the index n-1. But this process require two times for loop. Is there any better approach which can do the same in efficient manner.
Or a more efficient way of doing this is to use a StringBuilder which is a wrapper for char[] and let it do it for you.
char[] chars = "Hello".toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(chars);
sb.replace(2, 4, "L");
System.out.println(sb);
prints
HeLo
You can look at the code for replace to see how it does it.
Copy array portions with System.arraycopy() instead of iterating over its elements.
Given that you want a new array object, there's no faster way than by copying each array element once, so there's no more efficient method than this. If you use two calls to System.arraycopy(), you don't have to write the loops yourself.
If you don't need a new array object, you could just move the higher-numbered array elements down by one, which involves just half the number of copies -- but then you're going to need to keep track of the length some other way.
It could use a single for loop. Just put in an IF statement indicating if iteration (i) = index you want to replace then do a different operation rather than just copy.
Written in basic:
For i = 0 to n - 1
If i = x then
arrayCopy(i) = replaceChars
Else
arrayCopy(i) = arraySource(i)
End If
Next

Categories