.

MathBits.com

   Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use  

Methods -- Style 3 

Style 3:  Our third style of method takes no arguments, but will return a value.  Up until now, we have been communicating information TO an invoked method.  Now we will be returning information FROM the method by using the method return value.  The return value can be a constant, a variable, or an expression.  The only requirement is that the return value be of the type specified in the method definition.    

A method call (that returns a value) is replaced by the method's return value when the method is finished ... so be sure to do something with that return value.  Store the return value somewhere; print the return value to the screen; use the return value in a calculation; just use it!! 

//Demo Program for Methods
import java.io.*;
import BreezyGUI.*;

public class method1test
{
     public static void main(String[ ] args)
    {
          greeting(5);  //first method call
          int response;
          response = getNumber();   //second method call
          greeting (response);          //first method call again
    }
 

     //First Method for greeting
     public static void greeting(int x)
    {
         int i;
         for(i = 0; i < x; i++)
         {
               System.out.print("Hi ");
         }
         System.out.println( );
    }


    //Second method which returns a number
    public static int getNumber( )
    {
         int number;
        do
        {
            number = Console.readInt("\nPlease enter value(1-10): ");
         }
        while ((number < 1) || (number > 10));  //error trap
        return number;  //return the number to main
    }
}

 

Hi Hi Hi Hi Hi

Please enter value(1-10): 5
Hi Hi Hi Hi Hi

                    
                     
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use