0

Prog: Assume a hotel having 5 floors with each floor 10 rooms. No of people allowed in each room is 4. Fill the matrix using random and print it in matrix format. and 1. Count total number of customers in the hotel 2. Display which room is free 3. If no of customers in a room is 4, print a message saying that extra bed charges!

import java.util.Random;

class HRooms
{

public static void main( String v[ ] )
{

int Tcount=0;
Random rnd  = new Random();
int avail[ ][ ] = new int [5][10];

for( int r=1; r<6; r++)
{       
     for( int c = 1; c<11; c++)
     {
       avail[r][c] = rnd.nextInt( 5 );
       Tcount=Tcount+avail[r][c];
     }
}

System.out.println("Rooms avail. list");
System.out.println("----------------------------------------");
for( int r=1; r<6; r++)
{       
     for( int c = 1; c<11; c++)
     {
       System.out.print(avail[r][c] + "  ");
     }
     System.out.print("\n");
}

System.out.print("\n");
System.out.println("Total number of customers in the hotel is "+Tcount);
System.out.print("\n");


for( int r=1; r<6; r++)
{       
     for( int c=1; c<11; c++)
     {
    if( avail[r][c]==0)
        {
            System.out.println("The room "+c+" in floor "+r+" is empty");
        }

    }
}

System.out.print("\n");

for( int r=1; r<6; r++)
{       
     for( int c = 1; c<11; c++)
     {

    if( avail[r][c]==4)
        {
            System.out.println("The room "+c+" in floor "+r+" has 4 customers, extra bed charges");
        }
    }
}

        }
    }

The output says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at HRooms.main(HRooms.java:18)

Whats the solution??

  • 2
    Java arrays are zero-indexed – JonK Jul 16 '14 at 08:57
  • Yeps, it's a convention which you can write entire books about, not all languages do it that way, but it's the de facto convention it seems. – Davio Jul 16 '14 at 08:58
  • possible duplicate of [java.lang.ArrayIndexOutOfBoundsException](http://stackoverflow.com/questions/5554734/java-lang-arrayindexoutofboundsexception) – BackSlash Jul 16 '14 at 08:58

2 Answers2

3

Indexes in arrays starts from 0, not 1.

So if you have arr[5], then it would be accessible from arr[0]-arr[4]

When you say avail[r][c]==0 for r=5 and c= 10 the you are actually accessing 6th row and 11th column which does not exist - hence Index out of bound.

so, this :

    for( int r=1; r<6; r++)
    {       
      for( int c = 1; c<11; c++)
      { //code }
    }

should be

for( int r=0; r<5; r++)
    {       
      for( int c = 0; c<10; c++)
      { //code }
    }
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
0

Indexes starts at 0 in java.

You have a sized array you want to fill so use the array dimensions for filling it :

for( int r=0; r<avail.length; r++)
{       
  for( int c = 0; c<avail[r].length; c++)
  {
    avail[r][c] = rnd.nextInt( 5 );
    Tcount=Tcount+avail[r][c];
  }
}

this way, you will not encounter any ArrayIndexOutOfBoundsException

neomega
  • 712
  • 5
  • 19