Home > database >  Array Not Printing - Arrays.toString()
Array Not Printing - Arrays.toString()

Time:12-06

There are no errors in my code, and I've used the Arrays.toString() function to print the array, but nothing is being displayed on screen when I run the code. How can I fix this?

import java.util.Arrays;

public class passedArray {

public static void passingArray(int[] nums) {
    
      int arr[] = {6, 3, 8, 89, 34, 89, 132, 76, 34, 89, 11, 9, 19}; 
      
      System.out.println(Arrays.toString(nums)); // <<< here

    int[] temp = new int[nums.length]; 
    for(int i = 0; i < nums.length; i  ) {
    temp[i] = nums[i]; 
    }
    
    int index = 0; 
    for(int i = 0; i < temp.length; i  ) {
        if(temp[i] % 2 ==0) { 
            nums[index] = temp[i]; 
            index  ; 
        }
    }
   
     for (int i = 0; index < temp.length; index  ) {
         if (temp[i] % 2 != 0) { 
             nums[index] = temp[i]; 
             index  ; 
             
         }
     }
     
    
 }  

}

CodePudding user response:

Your line System.out.println(Arrays.toString(nums)); prints the passed argument nums, not the array you created named arr.

Try:

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

Full code example.

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int[] x = { 7 , 42 } ;
        Ideone.passingArray( x ) ;
    }

public static void passingArray( int[] nums ) {
    
      int[] arr = { 6, 3, 8, 89, 34, 89, 132, 76, 34, 89, 11, 9, 19 }; 
      
      System.out.println( "nums = "   Arrays.toString( nums ) ); 
      System.out.println( "arr = "   Arrays.toString( arr ) ); 
}

}

See this code run live at IdeOne.com.

nums = [7, 42]

arr = [6, 3, 8, 89, 34, 89, 132, 76, 34, 89, 11, 9, 19]

CodePudding user response:

Try System.out.println(Arrays.toString(arr));

  • Related