THIS java.lang.ArrayIndexOutOfBoundsException ERROR - java

public static int StringInString(String one, String two) {
if(one==null||two==null||one.equals("")||two.equals("")){
return 0;
}
else{
int x=one.length(),y=two.length(),sum=0,i=0,j=0;
char[] onee=one.toCharArray();
char[] twoo=two.toCharArray();
while(i<x){
while(j<y){
if(onee[i]==twoo[j]){
i++;
j++;
}
else{
if(j==0){
i++;
}
else{
j=0;
i++;
}
}
}
sum++;
i=i-y+1;
j=0;
}
return sum;
}
}
public static void main(String[] args){
int sum;
sum = StringInString("salamsal","sal");
System.out.println(sum);
}
hello I dont know why this ERROR apear?! please HELP me;
this code want count the similar text in two stringsa
and the result of this code should be = 2.

When you are inside the second "while" cycle, even if i > x, the cycle continues as long as j < y. So when it happens that i++ in the second cycle makes i become greater than x-1, and j is still less than y, in the first "if" (always inside the second while cycle) the program tests if onee[8] == twoo[0], and since onee[8] doesn't exist (because the indexes of "salamsal" go from 0 to 7) it shows the error that the index is out of the array bounds. To solve the error you should check for the value of i inside the second cycle, because it may happen that i++ makes this index become greater than x-1, where x is, as you declared, the length of the first string.

Related

getting hash values while trying to increment the value inside for loop in a java program

I'm trying to get the output of 8 through this loop condition but I am getting this value instead:
-2147483648
class Test1 {
public static void main(String [] args) {
int p = 2;
int j=5;
for (int i = p; i < j; i++) {
j++;
}
System.out.println(j);
}
}
Why is it happening and where do I need to look into?
In your loop, you're incrementing both i and j. That means that i < j is going to be true for several iterations.
Eventually, j reaches the largest possible int; which means that the next time you increment it, it will flip to the smallest possible int. Finally, it's less than i, so the loop will break. Therefore, the final value of j, at the end of your program, is the smallest possible int, which is -2147483648.

Calculating the factorial of every element in an integer array

I need to create a Method that has 2 parameters in Java, upperborder and lowerborder. This method must create an array from the number 2 to the number 10.
Then I must implement another method, that calculates the factorial for a given number.
Then I must implement a third method that calculates the factorial for every element in the created array and test all these methods in a TestClass.
I know how to do this, but apparently I'm making some kind of a mistake in my code and it gives me the StackOverflow exception. I read the code a couple of times, but I can't seem to quite understand where I'm wrong.
package fakultaetinarray;
public final class FakultaetinArray{
private int i;
private int[] a;
private int j;
public FakultaetinArray(){
System.out.println("Given array : ");
createArray(1, 9);
System.out.println("Factorial for every element : ");
FakinArray();
}
public int fakRe(int n){
if(n == 1){
return n;
}
return n * fakRe(n - 1);
}
public void createArray(int untergrenze, int obergrenze){
this.a = new int[obergrenze];
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
}
public void FakinArray(){
a[0] = 2;
for(i = 1; i < a.length; i++){
int fak = fakRe(a[i]);
a[i] = fak;
System.out.println(fak);
}
}
}
The reason you're getting StackOverflowErrors is due to your recursive method not having a case when n == 0.
The reason that your values are coming in as 0 is due to how you're constructing your loop.
for(this.j = 1; j <= a.length; j++){
a[i] = j + 1;
System.out.println(a[i]);
}
It's unclear why you're using j here at all, and i is initialized to its default value of 0, so in all reality, you're only ever filling one element of your array with a positive value and all of the others are at zero.
You need to reconsider how your loops are constructed. I would strongly encourage you not to make them fields, but declare them as part of the loop construct instead.
if(n == 1){ is not a strong enough condition to block the recursion: n can go below 1. In your particular case, you have a situation where n is 0.
Consider unwinding the recursion to a simple loop in any case. As a rule of thumb, recursion is not good for O(N) stuff.

Quicksort Stack overflow error

while practicing for an exam I encountered a (for me) strange issue with quicksort.
My implementation:
public void quicksort(int l, int r)
{
if(l<r && l>0 && r<=array.length-1)
{
int pivot = array[pivot(l, r)];
int i = l;
int j = r;
if(j==i+1)
{
if(array[i]>array[j])
{
System.out.println(array[i]+"<->"+array[j]);
int help = array[i];
array[i] = array[j];
array[j] = help;
}
}
else{ while(i<=j)
{
if(array[i]>=pivot && pivot>= array[j])
{
System.out.println(array[i]+">="+pivot+">="+array[j]);
int help = array[i];
array[i] = array[j];
array[j] = help;
i++;
j--;
}
else{
i++;
}
}
if(l<j && j<array.length-1)quicksort(l, j);
if(i<r)quicksort(i, r);
}
}
}
But this is giving me a "Java.lang.StackOverflowError: null" in (here) Line 34. This Error can, however, be avoided by swapping j with j-1 and i with j in Lines 34 and 35. I really tried everything that came into my mind, but I really cannot come up with a solution :/
I think there are much better implementations of quicksort, here is my attempt with commentary which will hopefully help you remember it better:
public static void quickSort(int[] theArray, int left, int right) {
//we declare 2 variables
int i = left;
int j = right;
//we calculate a pivot, simply taking the middle value of the array
int pivot = theArray[(left+right)/2];
//check that i hasn't gone beyond j (i starts at 0, j starts at array.length)
while(i<=j){
//if here, must mean i is less-than or equal to j, so check to see if
//the array value i is less than our pivot
while(theArray[i] < pivot){
//if it is less-than pivot, the value theArray[i] is in correct place
//so we can increment i to go to next
i++;
}
//now do exactly same thing for j, however, j starts at array.length, so decrement
while(theArray[j] > pivot){
j--;
}
//if we are here, it likely means we need to swap values
//check that i hasn't gone beyond j
if(i<=j){
//simple swap
temp = theArray[i];
theArray[i] = theArray[j];
theArray[j] = temp;
//we just swapped values, so we don't need to check them again, so continue
i++;
j--;
}
}
//now check if parameter left is < j
//if left has gone beyond j, it means we no longer need to further sort
if(left<j){
//rinse and repeat
quickSort(theArray, left, j);
//and check that i is still less than right parameter
}if(i < right){
//rinse and repeat
quickSort(theArray, i, right);
}
}
Usage:
//you can amend this code so you don't have to pass in an array
quickSort(theArray, 0, theArray.length-1);
It's fairly simple once you understand what quicksort is trying to do. Don't stress out about it, take a 15minute break, watch a graphical representation of the algorithm and think about how the code should behave and what it's trying to achieve. Come back here, look at the code, and start implementing it. Rinse and repeat! Good luck!
Also (not sure how your exam layout is) but you could also mention that to near-enough guarantee runtime of O(n log n), you really ought to shuffle the array before hand.

what is wrong with my backtracking algorithm? (sudoku solver, stackoverflow)

below is a method to solve a sudoku with backtracking algorithm.. or that's what I meant to do
private boolean fillGrid(int[][] a){
if(!find(a)) // this method finds if there's unassigned grid
return true;
for(int i = 0; i<a.length ; i++){
for(int j = 0; j < a.length ; j++){
if(a[i][j] == 0){ // if a[i][j] is unassigned, perform things below
for(int num = 1 ; num <=9; num++){
if(noConflict(a, i, j, num ) && noConflictGrid(a, i, j , num))
a[i][j]= num;
if(fillGrid(a)) // recurse
return true;
a[i][j] = 0; // unassigned to try again whenever false;
}
}
}
}
return false;
}
however when I run it, it gave me stackoverflow. the stackoverflow points to fillGrid(a) the one with 'recurse' comment, and (!find(a)). the method find is below:
private boolean find(int[][] a){
for(int[] b: a){
for(int c: b){
if(c == 0)
return true;
}
}
return false;
}
anyone please tell me what's wrong with the code?
if(noConflict(a, i, j, num ) && noConflictGrid(a, i, j , num))
a[i][j]= num;
Are you sure this is always guaranteed to be true? If it's not, the state of a doesnt change before the next call to fillGrid(a) and we go back to square one, calling the same method with the same input. Which lead to a stackoverflow.
You are creating a lot of branches on each step.
I recomend you to take one cell on each step and try to fill it with the 9 numbers, so you will only carry on with the valid.
Right now you are creating up to 9*9*9 branches on every step, you recursion is too much complex and this is was is creating the stack overflow.
So in every step just seek for the first free cell (with lower i and j index) and try to fill it with the 9 numbers.

Recursive method to print array [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 6 years ago.
This is the method code:
public static void printMatrix(int[][] m, int i, int j) {
if (i == m.length ||j==m.length) {
System.out.println();
} else {
System.out.print("[" + m[i][j] + "]");
printMatrix(m, i, j++);
printMatrix(m, i++, j);
}
}
I donĀ“t know why it just prints the first position of the array until a StackOverFlow error.
Thanks for the help.
You call 2 times the recursive function, but it keep calling itself with i and j..
printMatrix(m, i, j++); << use ++j
printMatrix(m, i++, j); << use ++i
Here is a possible solution for you
public static void printMatrix(int[][] m, int i, int j)
{
System.out.print("[" + m[i][j] + "]");
if (i == m.length && j == m.length)
{
return;
}
if (j == m.length)
{
j = 0;
++i;
printMatrix(m, i, j);
}
else
{
j++;
printMatrix(m, i, j);
}
}
non-recursive
public static void printMatrix(int[][] m)
{
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m.length; j++)
System.out.print("[" + m[i][j] + "]");
}
If you're trying to print each element of the matrix once, then none of the solutions in the other answers [EDIT: I guess we're down to one answer now] is going to help. The most they will do is get rid of the stack overflow error, but the output is still not going to be close to what you need.
Assuming this is a homework assignment and you've been told to use recursion for some reason (in real life nobody would do that), you have to step back and think about this: just what do you want printMatrix(m,i,j) to do? Presumably, you want to print the m[i][j] element, and then call printMatrix to print the rest of the matrix. When you call printMatrix recursively to start the printing rest of the matrix, what do you want i and j to be? Probably, you want the same i and the next column, j+1, but not if j is at the end of the row. Then you want ... I'll let you think about that. But I don't think you want printMatrix to call itself twice. Instead, you want it to call itself only once (at most); you'll probably need an if statement that looks something like
if(something)
printMatrix(something);
else
printMatrix(something different);
but it will still call itself only once (since it will pick one or the other).
I'll mention one other thing: you're comparing i to the number of rows in the array (m.length), but you're also comparing j to the number of rows in the array. That's fine if you know this is a square matrix. But if you want to compare j to the number of columns, compare it to m[i].length, since m[i] is itself an array (that represents one row of the matrix).
The size of array 'm' will be constant through out the recursive calls. Whereas the value of of i and j will be changing and base condition will be only satisfied once that. So it infinitely enter the base condition was the same i and j. That is why i guess it keeps printing only one value and after sometime the stack overflows. i do not really view this as proper use of recursion. Correct me if i'm wrong. when using recursion a problem reduces size as function calls are made till it is broken into the smallest unit possible, which can be identified by the base condition or the breaking point. I don't see this happening here.
public class Printarray {
static int max= 2;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int array[]={1,2,3};
print(array,0);
}
public static void print(int array[],int i)
{
System.out.println(array[i]);
if(i==Printarray.max)
{
Printarray.max--;
return;
}
else
{
print(array,i+1);
}
}
}
This works for 1D array, you can try this for 2D arrays and see if it works.
I hope it helps!
private static void print(int[][] mat, int i, int j) {
// TODO Auto-generated method stub
if(mat==null){
return;
}
if(i==mat.length || j==mat[0].length){
return;
}
System.out.print(mat[i][j]+" ");
if(j==mat[0].length-1){
System.out.println();
print(mat,i+1,0);
}
print(mat,i,j+1);
}

Categories

Resources