Friday 2 September 2011

Java: A Simple Programs Using Methods

    Bam, late update! Been busy, and seeing as I have no followers, who cares, really?
    Some basic programs we can practice with, I'll take directly from the book for ease. First is the multiplication table program, a trivial program to ask for input on which multiplication table you want displayed from 2 to 12 inclusive. The program rejects any invalid input.
    Let's start with the statement of problem, which is pretty much summed up above:


Statement of Problem:
   Write a program that uses a method to display a multiplication table given an integer between 2 and 12 inclusive. The program should ask the user which table to display, and reject any invalid request.

Design and Implementation
   First and foremost, we need the method to actually display the multiplication table, call it something easy to remember and understand, but try not to make it too irritating to keep typing out."displayTable" works nicely. Since it requires input to know what to output, it'll take the integer as a parameter, and printing out the result means there need be no return value.
    Another method needed is the main method, which is required, as previously discussed, by the program to actually run. So do we place the user input collection in here, or do we need another method to handle that? Mostly, in programming, you want each method used to be really good at what it does, but to limit what it does exactly to 1 small thing. Using this method, the main function can focus on initializing the program through creating an object (every method needs to be applied to an object, remember), then calling another method to take input. This new method can then focus on taking input before calling the displayTable method, lets call it doTable. So now we have our design ready, and determined a hierarchy.     Although this is technically the right way to do things, I will mention that I prefer putting the input gathering in the main function anyway, although I tend to write smaller programs for use by myself only. Just sayin'.     Now we have this hierarchy, though, and know what each method does in relation to each other, we needn't worry about the big picture, only working on small, easily manageable chunks at a time. If the design is right (which is why planning before writing the program is important, saving countless hours), not needing to focus on the functionality as a whole is immensely time saving, and stress relieving. Make sure each cog does its job well, and the machine should be fine.

    Now we're concerned with the design of each method (Or not, in this case, as it's relatively simple). displayTable needs a loop to go through the table, and an output to display it. doTable will take input, check acceptable range, and if it is, call displayTable with that input.. Otherwise, display an error message.



import java.io.BufferedReader;
import java.io.InputStreamReader; //imports required for input functionality!


public class MultiplicationTable {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static String input = null;

    public static String getInputStr() throws IOException {
        input = br .readLine();
        return input;
    } //Input functionality


    private void displayTable( int n ) { //This is private since it is meant to be used by another 

                                                             //method, no need to be public, encapsulation and all that.
        int counter = 1;
        System.out.println("The " + n + " times table");
        while ( counter < 13 ) {
            System.out.println( counter + " x " + n " = " counter * n );
            counter += 1;
        }
    }

    private void doTable() {
        System.out.print("Which times table to display? (2-12) ");
        int x = Integer.parseInt ( getInputStr() ); //Remember, the user input is taken as a string, 

                                                                                  //you need to parse it to get an integer!
        if ( ( x < 2 ) || ( x > 12 ) ) { //2 vertical bars means "or"
            System.out.println("That is not a valid times table to display!");
        } else {
            displayTable( x );
    }

    public static void main(final String[] args) {
        MultiplicationTable object = new MultiplicationTable();
        object.doTable();
    }






    And that's it for this program! Easy, right? Now try to do one yourself. A pretty standard example seems to be a palindrome program using recursion (test if the input given is a palindrome or not, return True or False respectively).

No comments:

Post a Comment