Jordan O
Posts: 7
Nickname: crowbar
Registered: Feb, 2011
|
|
Re: a little challege
|
Posted: Feb 19, 2011 9:49 AM
|
|
First off your code is a mess, I recommend working on your coding style so that its easily readable.
It looks like you are having trouble understanding how composition should be used. Some of the code is superfluous but I tried to leave the methods as close to your original as I could. This code will do what you want it to:
import java.util.Scanner; /* * @author */ public class RectangleTest{ /** * @param args the command line arguments */ public static void main(String[] args){ // creates instance of rectangle named myShape Rectangle myShape = new Rectangle(); myShape.setRec();
} }
class Rectangle { //creates scanner Scanner input = new Scanner(System.in); private int length = 0; private int width = 0; public void setRec (){ //gathers the users input for the length of the shape System.out.println("Please enter the length of the shape: "); length = input.nextInt(); //gathers the users input for the width of the shape System.out.println("Please enter the width of the shape: "); width = input.nextInt(); System.out.println(this.getPerimeter()); if (length != width) { System.out.println(this.getArea(length, width)); }else{ System.out.println(this.getArea(length)); } } /** * Returns the shape parameters * @return */ public String getPerimeter (){ int perimeter = (length * 2) + (width * 2); return String.format("Perimeter is %s\n", perimeter); } /** * when called this method will set both the length and width * of the shape * @param length * @param width */ public String getArea (int length1, int width1){ length = length1; width = width1; return "The rectangle is " + length*width + " units squared"; } /** * when the getArea method is called for a square it will set the width * and the length are equal to the width (all sides are equal) * @param length */ public String getArea (int length1){ width = length1; length = length1; return String.format("A square is %s\n by %s\n",length, width); }
}
|
|