Tank Program For Java
Tank Program For Java
Tank Program For Java
-
Question
Write a JAVA program to create a two-dimensional array called ‘tank’ of size r×c,
where r is row and c is column value. Array tank holds water after walls are built in it.
Array tank can only have vertical walls.
Output of the program:
1. Print the tank.
2. How many units of water the tank holds?
Process of input in tank array:
Ask the user how many blocks of wall each column will have, insert those blocks from
the bottom of each column.
EXAMPLE 1:
A tank array of size 5x7 is shown below: tank-1
0 0 0 0 0 0 0
1 0 0 0 0 0 0
1 x x x x 1 0
1 x 1 1 x 1 0
1 x 1 1 x 1 0
This tank array has four vertical walls at column 1, 3, 4 and 6. ‘X’ is a unit of water
stored in the tank. It holds 8 units of water.
Algorithm:
Step 1: Begin
Step 2:[Creating objects and initializing variables]
Creating Scanner class object to accept data.
Integer variables r and c are initialized . A character array a is also initialized. An
integer array brick is initialized
r user input
c user input
a[ ][ ]r,c
brickc
For(i0 to c)
{
nbsc.nextInt();
brick[i] nb;
For(jr-1 to r-nb)
jj-1;
}ii+1;
For (i0 to c)
If(brick[i]>0)
For(ji+1 to c)
If(brick[j]>0)
If(brick[i]<brick[j])
For(lr-1 to r-brick[i])
If(a[l][k] ! '1')
{
a[l][k] 'X';
}ll+1;
}kk+1
Else If(brick[i]>=brick[j])
For(ki+1 to <j)
For(lr-1 to r-brick[j])
If(a[l][k]! '1')
a[l][k] 'X';
}ll+1;
}kk+1;
} } } jj+1; } }
ii+1;}
For(i0 to <r)
For(j0 to c)
jj+1;
}Print : “ ”
ii+I;
}
Step 7: End
Source Code:
import java.util.*;
class Tank
int i,j,k,l,r,c,nb;
r=sc.nextInt();
c=sc.nextInt();
for(i=0;i<c;i++)
{
brick[i]=nb;
for(j=r-1;j>=r-nb;j--)
for(i=0;i<c;i++)
if(brick[i]>0)
for(j=i+1;j<c;j++)
if(brick[j]>0)
if(brick[i]<brick[j])
for(k=i+1;k<j;k++)
for(l=r-1;l>=r-brick[i];l--)
if(a[l][k]!='1')
{
a[l][k]='X'; //Storing the
water as X
else if(brick[i]>=brick[j])
for(k=i+1;k<j;k++)
for(l=r-1;l>=r-brick[j];l--)
if(a[l][k]!='1')
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
if((a[i][j]!='1')&&(a[i][j]!='X'))
a[i][j]='0';
for(i=0;i<r;i++)
for(j=0;j<c;j++)
System.out.println();
Variable description
Variable Data Type Purpose
i integer Iteration
j integer Iteration
k integer Iteration
l integer Iteration
Method Description
Methods Description
main() Comprises the program, to input the
number of rows, columns and bricks
and print a tank
nextInt() Accepts integer from the user
Scanner(...) Parameterised Constructor
Class Description
Class Description
Tank User Defined Class to , to print a tank