Results 1 to 5 of 5

Thread: Initailization

  1. #1
    Kartiky14 is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Initailization

    if(y%4==0)
    {
    int day[]= {30,29,30,31,30,31,31,31,30,31,30,31}
    else{
    int day[]= {30,28,30,31,30,31,31,31,30,31,30,31};}
    Can a array be initialized like the above way and then be used in a enhanced for loop somewhere in the program ?????

  2. #2
    mwr1976 is offline Senior Member
    Join Date
    Oct 2011
    Posts
    106
    Rep Power
    0

    Default Re: Initailization

    Did you try this code?What happened? What do you mean by "be used in a enhanced for loop"?

  3. #3
    Kartiky14 is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Initailization

    Quote Originally Posted by mwr1976 View Post
    Did you try this code?What happened? What do you mean by "be used in a enhanced for loop"?
    Yes i did and a compilation error popped...of the the array not been found at the looping statement
    well i call this an enhanced for loop :P
    for(int <initialization variable>:array)
    {}

  4. #4
    mwr1976 is offline Senior Member
    Join Date
    Oct 2011
    Posts
    106
    Rep Power
    0

    Default Re: Initailization

    Here's more than enough to get you going in the right direction. The one thing you have to be cognizant of in taking this approach, is in what ways shallow or deep copying will affect the processing of your application.

    start here:
    Java Code:
    	static Scanner console = new Scanner(System.in);
    	public static void main(String[] args)
    	{
    		int y;
    		
    		System.out.println("Enter:");
    		y = console.nextInt();
    		
    		int[] day = new int[0];
    		if(y % 4 == 0)
    		{
    			int[] days = {1,2,3};
    			day = days;
    		}
    		else
    		{
    			int[] days ={5,6, 7, 8, 9,0};
    			day = days;
    		}
    		
    		for(int n : day)
    		{
    			System.out.print(n + " ");
    		}
    
    	}

  5. #5
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    7

    Default Re: Initailization

    It means that your day array is not accessible within the for-each loop block. This is happen because your day variable is declared inside the if statement block. To let the for block have access to it, declare your array before the if block. You can the initialize it inside your if block and iterate it using the for-each statement.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •