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
Related
I want to return a value from a for-if statement in java but unfortunately i am not able to do so.
I did try to return a value from inside a if statement from a for loop, but got an error
You have missing return statement because every branch of the code should return something, here in case the array is empty, then you don't do anything of the loop you'll have no return
Then you have put the else in the loop, so if the first number is not the one loop you for you return -1 meaning not found.
You need to wait the whole loop before being able to tell that you didn't find it
And that behaviour fix, solves the syntax issue too
public int search(int[] nums, int target){
for(int i=0; i<nums.length; i++){
if(nums[i] == target)
return i;
}
return -1;
}
The problem with your code (using you image here):
Even though you have the return inside the IF statement and the ELSE statement, they will only be reached only IF the code gets inside the FOR statement.
What would happen if you call your method with an empty nums array? if would skip the for statement and there is NOTHING to return for your method in this case, do you get it?
That's why you need a return outside the for/loop as well, meaning that: What your method wants to return if reaches this point?.
If it is a search, for example, you could return -1 outside the FOR/Loop and remove the ELSE statement from inside.
Don't wanna change to much your code, so you clearly see the difference, since you are clearly starting:
public int search(int[] nums, int target) {
int i;
int j;
int n = nums.length;
for (i=0;i<n;i++){
if (nums[i]==target) {
return (i);
}
}
return (-1);
}
Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.
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!!");
}
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.
So I have a program that deals with bytes. Everything works, except one part. A for loop doesn't execute at all.
This is the code...complex it is.
public int getID(int slot){
int slots = 0;
for(int a=0;a<b.length;a++){
if(correctslot){ //condition not shown.
if(slots==slot){
System.out.println("found pair");
for(int i=a;i<37;i++){
System.out.println("executing loop");
if(isID){ //condition not shown.
System.out.println("returning location");
return i+1;
}
}
}
slots++;
}
}
return 0;
}
If the program found a matching slot, it prints found pair. If it was executing the loop it prints executing loop, but that's the part that doesn't do anything at all. It prints the first string found pair but not the second executing loop. What did I do wrong?
Debug a . I think a >= 37 by the time either correctSlot && slots == slot .