Search code examples
javaarraysexceptionstoreindexoutofboundsexception

array program to store a certain value from one array to another giving wrong output while running the below code in java


package Starter_Code;

public class Solution {

public int[] checkNumber(int[] inIntArr1,int[] inIntArr2) {
    int[] outIntArr=new int[inIntArr1.length];
    int temp,pro=1;
    
    int k=0;
    for(int i=0;i<inIntArr1.length;i++){
        for(int j=0;j<inIntArr2.length;j++){
            if(inIntArr1[i]==inIntArr2[j]){
                outIntArr[k]=inIntArr1[i];
                k++;
                break;
            }else if(Math.pow(inIntArr1[i], 2)==inIntArr2[j]){
                outIntArr[k]=inIntArr1[i];
                k++;
                break;
                
            }else if(inIntArr1[inIntArr1.length-1]==inIntArr2[inIntArr2.length-1]){
                outIntArr[k]=inIntArr1[i];
                k++;
                break;
            }else{
            
                while(inIntArr1[i]>0){
                temp=(inIntArr1[i])%10;
                pro=pro*temp;
                inIntArr1[i]=inIntArr1[i]/10;
                }
                if(pro==inIntArr2[j]){
                    outIntArr[k]=inIntArr1[i];
                    k++;
                    break;
                }
                
            }
            
            
         }
    }

    return outIntArr;
}

}

package Starter_Code;

public class Tester {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] inIntArr1= {26,17,25,35,39,63};
    int[] inIntArr2= {26,671,11,21,14,28};
  //Create an object of Solution
    Solution sol = new Solution();
    
    //Call checkNumber()
    int[]  result = sol.checkNumber(inIntArr1, inIntArr2);
    
    //display the output 
    System.out.println(result);
}

}

in this code i have to store the vales of inIntarr1 to outIntArr based on the condition which i have given in if statement and the length of outIntArr should be with in the range of inIntArr1, but the output is something like this [I@7a8ce1e1


Solution

  • Printing directly an array will give you the hashcode always. change your code like below and will get the readable format output.

    Current code:

    //display the output

    System.out.println(result);
    

    Suggested code: Try this

    // display the output

    System.out.println(Arrays.toString(result));