/** * Modularity.java * * @author Jeff Ondich * * This program illustrates methods. * * 1. Read the code to see whether you can guess what's going to happen * when you run it. Then compile and run it. * * 2. The "methods" printGreeting and sumOfIntegers take care of special * tasks for main. Note one advantage of delegating authority from main * to a separate method--main calls sumOfIntegers twice, but the code for * sumOfIntegers only has to appear once in the program. Thus, you gain * a lot of efficiency by putting a frequently used block of code into * a method, and calling the method whenever you need to use that block of * code. * * Breaking your overall program into small subtasks and putting the subtasks * into methods is called "modular programming," and it's one of the central * tools programmers use to control the immense complexity of big programs. * We'll talk a lot more about modularity as the term continues. * */ import javabook.*; class Modularity { public static void main( String[] args ) { // Get ready to talk to the us. MainWindow mw = new MainWindow(); mw.setVisible( true ); mw.toFront(); OutputBox out = new OutputBox( mw ); out.setVisible( true ); out.toFront(); InputBox in = new InputBox( mw ); // Call a couple methods. printGreeting( out ); int number, sum; number = in.getInteger( "Number, please:" ); sum = sumOfIntegers( number ); out.printLine( "The sum of the first " + number + " integers is " + sum ); sum = sumOfIntegers( number * number ); out.printLine( "The sum of the first " + (number*number) + " integers is " + sum ); } static void printGreeting( OutputBox box ) { box.printLine( "Avast there, ye scurvy user." ); } static int sumOfIntegers( int n ) { int total = 0; int j = 1; while( j <= n ) { total = total + j; j = j + 1; } return total; } }