Discussion Section 4: More on Methods
Due: 10pm Tuesday February 13
Purpose: In this discussion section, you will
practice how to use parameters in methods.
Let's print a triangle.
Please enter the size of a triangle, or 0 to quit: 3
*
**
***
Please enter the size of a triangle, or 0 to quit: 4
*
**
***
****
Please enter the size of a triangle, or 0 to quit: -1
Please enter the size of a triangle, or 0 to quit: 2
*
**
Please enter the size of a triangle, or 0 to quit: 0
Thanks!
Your program should include a method printTriangle. The signature
is as follows:
public void printTriangle(int size)
Implement this method to print a triangle of the given size. Your main method should not print any stars(*). If the first input is not an integer greater than 0, then your program should ask again for input. It is okay to simply repeat to ask the next input as shown above, but feel free to use your imagination for error message.
Here is a template for MTriangles.java.
import java.util.*;Once you are done with implementing MTriangles.java as described above, try to implement printTriangle to print a triangle with a given symbol. A sample scenario is given below.
/**
* @author name 1: discussion section time:
* @CS account user name:
*
* @author name 2: discussion section time:
* @CS account user name:
*
* @version Date
*
*/
public class MTriangles {
// constructor
public MTriangles() {
// Hint: nothing needs to go here
}
public void printTriangle(int size) {
// print a triangle of the width of "size" given as parameter
// Hint: reuse the code from the discussion section 2
}
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
MTriangles mt = new MTriangles();
System.out.println("Let's print a triangle.");
// initialize a variable which records the input for size
// Hint: what type of variable should it be? what should be the initial value?
// initialize a variable for the loop condition
// Hint: what type of variable should it be? what should be the initial value?
// loop starts here
// Hint: what should be the termination condition of this loop?
// print "Please enter the size.."
// read the input from user and store in the variable
// if the size is not 0
// call the method printTriangle
// Hint: printTriangle is non-static method
// else (if the size is 0)
// set the boolean variable to stop the loop
// loop ends here
// print "Thanks!"
}
}
Let's print a triangle.The new signature of the printTriangle method is as follows:
Please enter the size and the symbol of a triangle, or 0 to quit: 3 #
#
##
###
Please enter the size and the symbol of a triangle, or 0 to quit: 5 ^
^
^^
^^^
^^^^
^^^^^
Please enter the size and the symbol of a triangle, or 0 to quit: 0
Thanks for playing!
public void printTriangle(int size, String symbol)
Your program should be internally correct (sound logic) and
externally correct (following java style guideline).