PDA

View Full Version : I would like to know How to Print a square with asterisks in java with while loop onl


amratif
Nov 28, 2013, 04:46 PM
i would like to know How to Print a square with asterisks in java with while loop only but with out for loop and with out any logic operations like: and or Or this code something like that if we enter 4 it should print
* * * *
* *
* *
* * * *
but it do some thing else like that

* **


*

Scanner input = new Scanner(System.in) ;

int squareside ;
System.out.print("Enter the side: ");
squareside = input.nextInt();

while ( squareside != -1 )
{
int xaxis = 0 ;
while ( xaxis < squareside )
{

if( xaxis == 0 ) {
System.out.print(" *") ;
}
else if( xaxis == squareside - 1){
System.out.print(" *") ;
}
else
System.out.print(" ") ;

xaxis ++ ;

}
int yaxis = 0 ;

while( yaxis < squareside )
{
if
( yaxis == 0 )
{
System.out.print(" *");
}
else if( yaxis == squareside - 1)

{
System.out.print(" *");

}
else

System.out.print(" ");
yaxis ++;
System.out.println();

}

System.out.print("Enter the side: ");
squareside = input.nextInt();
}

Scleros
Nov 29, 2013, 07:15 AM
Your algorithm is fundamentally flawed if you are intending to print out each line (X axis) in sequence (Y axis). Scanner (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) objects also need some housekeeping done when finished with them.