import java.text.DecimalFormat;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Collections;
import java.util.Iterator;
import uwcse.io.Input;
/**
* Illustrating the use of loops
*/
public class Loops {
/**
* Draw a rectangle of stars
* @param lines the number of lines of the rectangle
* @param cols the number of columns of the rectangle
*/
public void drawARectangleOfStars(int lines, int cols)
{
for(int line=1; line<=lines; line++)
{
// if 1 statement only,{ and } are optional
// print cols "*"
for(int col=1; col<=cols; col++)
System.out.print("*");
// next line
System.out.println();
}
}
/**
* Draw a rectangle triangle of stars (right angle in the lower left)
* @param lines the number of lines of the triangle
*/
public void drawATriangleOfStars1(int lines)
{
for(int line=1; line<=lines; line++)
{
// print line "*"
for(int col=1; col<=line; col++)
System.out.print("*");
// next line
System.out.println();
}
}
/**
* Draw a rectangle triangle of stars (right angle in the lower right)
* @param lines the number of lines of the triangle
*/
public void drawATriangleOfStars2(int lines)
{
for(int line=1; line<=lines; line++)
{
//print lines-line spaces
for (int col=1; col<=lines-line; col++)
System.out.print(" ");
// print line "*"
for(int col=1; col<=line; col++)
System.out.print("*");
// next line
System.out.println();
}
}
/**
* Don't use a double to count in a loop
*/
public void countingWithADouble()
{
DecimalFormat d;
// Display with 15 digits
d = new DecimalFormat("0.000000000000000");
for(double x=0; x<10; x+=0.2)
System.out.println("x="+d.format(x));
}
/**
* Parse a String (print every word of a String separated by whitespaces)
* E.g. if s is "Hello, how are you?", the words "Hello,", "how", "are", "you?"
* are printed (one on each line).
* @param s the String to parse
*/
public void parseAString(String s)
{
StringTokenizer st = new StringTokenizer(s);
// By default, st uses a whitespace delimeter
// for parsing (other options are available)
while(st.hasMoreTokens())
System.out.println(st.nextToken());
}
/**
* Input, sort and print a list of integers
* (using some of the libraries of Java)
* We will see Collections by the end of the quarter.
*/
public void inputSortAndPrint()
{
// Ordering a list of positive integers
Vector v = new Vector(); //an implementation of
//a list (in java.util)
int i;
Input input = new Input();
// Get the integers
do{
i=input.readInt("Enter an integer(<0 to stop): ");
if (i>=0) v.add(new Integer(i)); //use a wrapper
}while(i>=0);
// Order the collection
Collections.sort(v); //in java.util
// Iterate through the collection and print it
Iterator it = v.iterator(); //in java.util
while(it.hasNext())
System.out.print(it.next()+" ");
// Blank line for a nice output
System.out.println();
}
}