Java – Drawing Squares
Posted Dec 5th, 2009 by Conor in in College, Java, LanguagesThis weeks ICSP assignment was to write a program which draws squares. The task was to draw squares from a set list in an array, but I opted rather to accept a command line argument in my script. To write this I had to delve back into regular expression, which I hate because I don’t understand!
The program source is below. You should execute the program from the command line giving the with and height of the square you wish to draw, for example:
java Squares 4x4
And the code:
import java.lang.String;
import java.util.regex.*;
public class Squares{
public int dimensions[];
public Squares(String[] args){
if(args.length==1){
Pattern form=Pattern.compile("^\\S+x\\S+$");
Matcher fit=form.matcher(args[0]);
if(fit.matches()){
try{
String[] dims=args[0].split("x");
int width=Integer.parseInt(dims[0]);
int height=Integer.parseInt(dims[1]);
this.dimensions=new int[] {width,height};
}
catch(NumberFormatException e){
System.err.println("Argument must be a string, width by height, in the form 6x6");
System.exit(1);
}
}
else{
System.out.println("Argument must be a string, width by height, in the form 6x6");
System.exit(1);
}
}
else{
System.err.println("Please supply an argument, which must be a string, width by height, in the form 6x6");
System.exit(0);
}
}
public String draw(){
int i;
int z;
int width=this.dimensions[0];
int height=this.dimensions[1];
String square="";
for(i=0;i<height ;i++){
for(z=0;z<width;z++){
if((i==0||i==height-1)&&(z==0||z==width-1))
square+="+";
else if(z==0||z==width-1)
square+="|";
else if((i==0||i==height-1))
square+="-";
else
square+=" ";
}
square+="\n";
}
return square;
}
public static void main(String[] args){
Squares square=new Squares(args);
String draw=square.draw();
System.out.println(draw);
}
}