10-17-2013

posted Oct 17, 2013, 8:37 AM by Samuel Konstantinovich   [ updated Oct 18, 2013, 11:27 AM ]
For loops:
for( initialize ;  boolean ;  increment ){
    //loop body
}
for example:

for( int x = 3; x < 10 ; x = x + 1 ){
    System.out.println("We are at:" + x);
}

Important note: Any variables declared inside the for loop , such as x will disappear when the loop ends. 


for example 2:
for( int x = 1; x < 1000 ; x *= 2 ){
    int i;
    //variable i does nothing, but won't exist outside the loop
    System.out.println(x);
}

LAB/HW:

0. You are going to write several methods. Since there is no object they are bound to you have to decide if you want them to be public/private, and if they need to be static. Answer this question before you continue.

1. Write a method String diag(int n) which will return a diagonal string of stars that will appear to be a diagonal line when printed. For example, diag(4) would return:
*
 *
  *
   *


2. You will need to know that a Strings have methods to access individual letters. Look at the string documentation to figure this out! Now write a method String diagWord(String w) which will return a string as above but using the letters of word w instead of using stars. For example, diagWord(“Hello”) would return:
H
 e
  l
   l
    o
Write a method String fence(int h, int w) which will return a String representing a fence. For example, a fence(5,8) would be a 5 by 8 fence that looks like:
5 by 8 fence:
+------+
|      |
|      |
|      |
+------+ 

2 by 4 fence:
+--+
+--+

1 by 4 fence:
+--+

1 by 2 fence:
++


SOLUTION
    public static String mult(String s,int i){
String ans = "";
while(i > 0){
   ans += s;
   i--;
}   
return ans;
    }


    //fill is a string that is repeated in the middle of 
    //the +'s at the endpoints. This should be " " or "-".
    public static String makeRow(int w, String fill){
if(w == 0)
   return "";
if(w == 1)
   return "+";
else
   return "+" + mult(fill,w-2) + "+";
    }

    public static String makeFence(int w, int h){
String ans = "";
//create an empty string to add onto
for(int count = 0; count < h; count++){
   //make 1 row per unit of h.
   if(count == 0 || count == (h - 1)){
//top and bottom row have -'s
ans += makeRow(w,"-") + "\n";
   }else{
//middle rows have spaces
ans += makeRow(w," ") + "\n";
   }
}
return ans;
    }
    

Comments