Java Basics
Methods 5 - Example with three methods
Purpose of this lesson:
- Show definition of multiple methods.
- All code is in methods.
- Style: The main method often consists largely of method calls.
- Style: Methods should generally be no larger than one page.
Here is another variation of the program, this time using three methods. Altho there is no real need for these methods in such a small program, large programs are in fact composed of many small methods. It is the essential way that all code is structured.
Each of the user-defined method names, both in the call and the definition, is hilited.
- One method is void, which means it doesn't return a value.
- Three methods call other methods.
- The main program consists mostly of calls to other methods.
Source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// File : methods/KmToMilesMethods.java // Purpose: Converts kilometers to miles using two methods. // Author : Fred Swartz - placed in public domain // Date : 22 Apr 2006 import javax.swing.*; public class KmToMilesMethods { //========================================================= constants private static final double MILES_PER_KILOMETER = 0.621; //============================================================== main public static void main(String[] args) { double kms = getDouble("Enter number of kilometers."); double miles = convertKmToMi(kms); displayString(kms + " kilometers is " + miles + " miles."); } //===================================================== convertKmToMi // Conversion method - kilometers to miles. private static double convertKmToMi(double kilometers) { double miles = kilometers * MILES_PER_KILOMETER; return miles; } //========================================================= getDouble // I/O convenience method to read a double value. private static double getDouble(String prompt) { String tempStr; tempStr = JOptionPane.showInputDialog(null, prompt); return Double.parseDouble(tempStr); } //===================================================== displayString // I/O convenience method to display a string in dialog box. private static void displayString(String output) { JOptionPane.showMessageDialog(null, output); } } |
Review Questions
[TODO]