This is a question in the book "Cracking the Coding Interview". Here is Java code, but why does it cause the ArrayIndexOutOfBoundsException? I just copied from the book.
class Q1_3{
public static void removeDuplicates(char[] str){
if(str==null) return;
int len=str.length;
if(len<2) return;
int t=1;
for(int i=1;i<len;++i){
int j;
for(j=0;j<t;++j){
if(str[i]==str[j])
break;
}
if(j==t){
str[t]=str[i];
++t;
}
}
str[t]=0; //why ?
}
public static void main(String[] args){
char ss1[] = {'a','b','c','d'};
char ss2[] = {'a','a','a','a'};
char ss3[] = {};
char ss4[] = {'a','a','b','b'};
removeDuplicates(ss1);
removeDuplicates(ss2);
removeDuplicates(ss3);
removeDuplicates(ss4);
System.out.println(ss1);
System.out.println(ss2);
System.out.println(ss3);
System.out.println(ss4);
}
}
It's really weird code, the naming and the use of control structures its... questionable...
The code breaks when there is no duplicated chars, t increases his value in all iterations and at the end is 4, this is what causes de exception.
in the example the code only crash with ss1, and "works" with the others.
If you debug the code closely, you will find that after comparing the value for the last element in the inner for loop you increment the value of t, thus the value of t will be str.length. But, array index start from 0 till str.length-1. So eventually, when you try to insert value at index str.length you will get the exception.
Related
I am learning Java programming and made a program which uses Binary Search to find a symbol in an array of char. However, I have a problem when I try to search for the symbol which is not in an array, my program becomes an endless cycle. I have no idea how to make an error sign if there is no such symbol in an array. Here is the code of my program
import java.lang.reflect.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args){
char[]arr = {'a','d','f','l','o','z'};
find(arr,'m');
}
public static void find(char[]arr,char ch){
int last = arr.length-1;
int mid=last;
while (arr[mid] != ch){
if (arr[mid]<ch){
mid = (last+mid)/2;
}
else{
last=mid;
mid=last/2;
}
}
System.out.print(mid);
}
}
Thank you in advance.
You have no case to break out of the while loop and the changed values assigned to the variables during the 2 if cases are incorrect. Plus, you should also check for when the element is found in the if-else ladder and use a variable (found) to indicate whether the element is found. Moreover, it'll be better if you use 3 variables for the lower bound (first), mid and upper bound (last). The code below is a revision of the find() method.
public static void find(char[]arr,char ch){
int first=0,mid=0,last=arr.length-1,found=0;
while (first<=last){
mid=(last+first)/2;
if(arr[mid]==ch){
System.out.print(ch+" found at index "+mid);
found=1;
break;
}
else if(arr[mid]<ch){
first=mid+1;
}
else if(arr[mid]>ch){
last=mid-1;
}
}
if(found==0)
System.out.print(ch+" was not found ");
}
This works fine and maybe you should use this method.
You have to make some changes in your find() method.First check that the value of mid should never exceed the value of last,so you have to change your while loop condition accordingly. Secondly you have to give a terminating condition if(arr[mid]==ch) to come out of the loop.
This can also be done by using two variables lo & hi ,easy to understand & implement.See the implementation here Binary Search.
Below is the solution using only only last & mid variables,as per your code requirement above:
public static void find(char[]arr,char ch){
int last = arr.length-1;
int mid=last/2;
while (mid<=last){
if(arr[mid] == ch) //if found, Print and exit the loop
{
System.out.println("found at:"+mid);
return;
}
if (arr[mid]<ch){
mid=((last+mid)/2)+1;
}
else{
last=mid-1;
mid=last/2;
}
}
System.out.println("Not found!!");
}
So for my Ap computer Science class One of my project keep getting java.lang.ArrayIndexOutOfBoundsException: 390000 Its a Sound reverse file
Here is the code:
import sounds.APSoundClip;
import sounds.Sample;
public class ReverseSound {
public static void main(String[] args) {
APSoundClip clip = new APSoundClip("money.wav");
APSoundClip newClip = clip.clone();
int pos = clip.getLength();
int cloned = 0;
for(Sample clipSample : clip) {
clip.getSample(pos); //error is here
int newValue = clipSample.getValue();
newClip.getSample(cloned).setValue(newValue);
pos--;
cloned++;
}
newClip.draw();
}
}
That seems like a "traditional" mistake - you initialize pos with int pos = clip.getLength();
Then at the first iteration you do clip.getSample(pos); - the last element is at index clip.getLength() - 1. You are trying to access the element at position clip.getLength(), that's why you are getting the index out of bounds error.
Java Arrays start with an index of zero, and because of this, their last index will be one less than their length. In your situation, you are assuming that clip.getLength()is the last element in the array, however, when you take a look at the anatomy of the array, it would really be clip.getLength()-1.
i am trying to print all size n binary numbers, for example if size is 3 , i want to print all numbers from 0 to (2^3)-1 in binary form, below if my code implementating, it prints 000 and gives me this error
"Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.getChars(String.java:854)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
at java.lang.StringBuilder.append(StringBuilder.java:119)
at java.lang.StringBuilder.<init>(StringBuilder.java:93)
at NBinary.tobinary(NBinary.java:11)
at NBinary.tobinary(NBinary.java:12)".
String temp = str+x; is line 11
tobinary(temp, size); is line 12
below is my code
public class NBinary {
static int arr[] = {0,1};
static void tobinary(String str,int size){
if(str.length() == size){
System.out.println(str);
}
for(int x : arr){
String temp = str+x;
tobinary(temp, size);
}
}
public static void main(String[]args){
tobinary("", 3);
}
}
please help me find the error. thanks
One problem is that you are not giving any Recursion Termination condition.
So the function recurses infinitely. No condition is there to cease the calling.
That is why the stack allocated for the function call runs out of space and you get StackOverflowError.
See more here:
http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html
What is a StackOverflowError?
I am working on some data structures - after searching for an element, I am attempting to delete that element - but throws
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at SearchArray.deleteElements(SearchArray.java:68)
at SearchArrayDemo.main(SearchArrayDemo.java:25)
this is my method
void deleteElements(int value)
{
int j,k;
for (j=0;j<setArray.length;j++)
if ( value == setArray[j])
break;
if
(setArray[j] == setArray.length)
System.out.print("no item found");
else
{
for( k=j;k<setArray.length;k++)
`setArray[k]=setArray[k+1];`
k=setArray.length-1;
setArray[j]=0;
System.out.println("item deleted");
}`
and main method used to call that functions deleteElements
sa.deleteElements(5);
I did not include all the code for conciseness, this is the line where code breaks
setArray[k]=setArray[k+1];
please let me know if remaining code is required. thanks all for your help.
The problem here is that your loop end condition is
k<setArray.length
, but then you use
setArray[k+1]
Change the condition to
k < setArray.length - 1
for( k=j;k<setArray.length;k++)
setArray[k]=setArray[k+1]; \\ K+1 (invalid index when k = setArray.length-1
In your code, this will fail for the last element. Hence you get the exception
In an Array last index will be Array.length-1. In your case for the last element the code fails because k=Array.length-1 (last index) and k+1 = Array.length (which does not exist). Hence it throws out of bounds exception.
Your first for loop has some dead-code:
if(setArray[j] == setArray.length)
System.out.print("no item found");
This condition will never be reached in your loop for (j=0;j<setArray.length;j++)
if u want to delete the element in array 4
class arrayserch{
public int value(){
int[] arr={1,2,3,4,5,6;
int i=0;
for(int a:arr){
if(a==4){
return i;
}
else
i++;
}
return=-1;
}
}
class example{
public static void main(string arags[]){
arrsearch as=new arrrsearch();
int i=as.value();
if(i!=-1){
arr.length--;
for(int j=i;j<arr.length;j++)
{
arr[j]=arr[i++];
}
}
}
this may solve ur problem
Problem is this snippet:
for( k=j;k<setArray.length;k++)
setArray[k]=setArray[k+1];
When k == setArray.length - 1, setArray[k+1] goes beyond setArray boundaries
i dont't know your code
but line
setArray[k]=setArray[k+1];
it's out boundaries array
I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.