Calling Methods

From CompSciWiki
Revision as of 15:00, 20 March 2007 by Ummisura (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > User-Defined_Methods


Introduction

A method consists of two parts: the method header and the method body. Each part is further broken down into smaller parts which are essential to describing what your method does, how your method will be called, what your method will process, and what your method will return.

   

{{{Body}}}

Introduction

Calling a method is like getting a screwdriver out of a toolbox labeled "screwdrivers" and then using it to solve your problem. Whenever JOptionPane.showInputDialog is called in Java, you are really telling Java to run the "tool" named showInputDialog which is located in the JOptionPane "toolbox".

You can write your own methods as well, this will be discussed later. For a full list of all the predefined methods, visit The Java API. Here are some predefined methods that are useful:

String Methods

equals()

This method compares two strings. The best way to think about it, is to think of it as a method that is applied to a string to see if it equals another. Example:

String testString;
testString = "I am test";

if testString.equals("I am test")
{
     //testString equals "I am test"
}
else
{
     //testString does not equal "I am test"
}

The above example would result in the if statement being true. It is important to note that equals() must be applied to a string variable.

equalsIgnoreCase()

This method is the same as the one above but the result will be true even if the cases are different. "I AM TEST" would be the same as "i am test".

For a full list of all the String methods you can visit: http://java.sun.com/javase/6/docs/api/java/lang/String.html (and then scroll down to the Method Summary table)

Math Methods

Math methods are very interesting. You can use them to help you in many applications that deal with numbers (e.g. banking system, lottery, cashier application, etc.). This section is introduced to help you understand how built-in math methods (in API) can be used within your code. These methods are very simple to use so there is no need to panic. You only need to call the method using the following general statement:

 Type variableName = Math.methodName(argumentList);
 
 Type         = double, float, or int.
 variableName = any name that suites your purpose.
 methodName   = round, min, sqrt, etc.
 argumentList = could be zero or more parameter(s).

Practice after each method introduced to improve your skills. You just need to know that the more you practice the method, the easier they will be.

Most used math methods (at least in COMP 1010):

round()

This method returns the argument passed (number) to the closest int.

 00  int n;
 01  n = Math.round(2.365);

The result of n is 2.

random()

This method returns a random double number between 0 and 1. It could be used to specify a range of numbers that you want your program to work with.

if you want to get a random number between 0.0 and 1.0:

00  double rand;
01  rand = Math.random();

between 1.0 and 11.0:

00  double rand;
01  rand = Math.random() * 10; // the number 10 increases the range to 10 numbers instead (0,1) range.

(Math.random() * n): n depends on the amount of numbers you require for the program. if you use n to be 15, then your range will be between 1.0 and 16.0:

00  double rand;
01  rand = Math.random() * 15;

For example, you want the numbers from 22 to 32:

00  int rand;
01  rand = (int)(Math.random() * 10) + 22; // 

Line 01 uses (int) to cast the double to int (be able to get an integer result).

you can use this method to pick a lucky number for a lottory application.

The formula for getting a random number between L (low number) and H (high number) inclusive is:

(Math.random() * (H - L)) + L

min()

This method returns the smaller of the two numbers passed to the min() method.

 00  int min1;
 01  double min2;
 02
 03  min1 = Math.min(3, 2);      // you can compare integers
 04  min2 = Math.min(1.2, 3.5);  // or you can compare doubles

The result of min1 is 2 and min2 is 1.2.

max()

This method returns the maximum number of the two numbers passed to the min() method.

 00  int max1;
 01  double max2;
 02
 03  max1 = Math.max(3, 2);      // you can compare integers
 04  max2 = Math.max(1.2, 3.5);  // or you can compare doubles

The result of min1 is 3 and min2 is 3.5.

pow()

This method (math.pow(x,n)) returns the result of x raised to the power of n.

 00  double power;
 01  power = Math.pow(2, 3);   // 2 to the power 3

The result of power is 8.

sqrt()

This method returns the square root of a positive number.

 00  double squareRoot;
 01  squareRoot = Math.sqrt(25);

The result of squareRoot is 5.

More Math methods and examples

For a full list of all the math methods you can visit: API Math Methods(and then scroll down to the Method Summary table)

To see an example about some Math methods you can visit: http://www.cafeaulait.org/course/week4/40.html

JOptionPane Methods

You have already seen JOptionPane being used for getting input from the user here, but you can do more with JOptionPane. Remember: in order to use JOptionPane methods, the top of your .java file must contain the following line:

import javax.swing.JOptionPane;

showInputDialog()

There are two different basic ways of calling showInputDialog. You've already seen the first one, which is simply by calling the method and sending the message as an argument:

String input;
input = JOptionPane.showInputDialog("Please enter input");

There is also a way of sending a default value for the input. After the message argument, add a comma and then enter the default value in between quotation marks:

String input;
input = JOptionPane.showInputDialog("Please enter a name", "Default Name");

The window will look like this:

ShowInputDialog.PNG

-Chris M:

JOptionPane.showInputDialog is also useful for getting other data types. In the next example, the String that is returned by showInputDialog is converted into an int with the Integer class' parseInt method:

String input;
int value;

input = JOptionPane.showInputDialog("Please enter a number");
value = Integer.parseInt(input);

showMessageDialog()

-Chris M

JOptionPane.showMessageDialog allows you to pop up a message window for the user:

JOptionPane.showMessageDialog(null, "Hello, world!");

Which results in:

ShowMessageDialog.PNG

Always use null as the first argument. The second argument is the String you would like to print out on the popup window.

More JOptionPane Methods

-http://java.sun.com/javase/6/docs/api/javax/swing/JOptionPane.html

Review Questions and Exercises

Review Questions

Question 1

How do you see if two strings are identical?

Question 2

Can you see if two Strings are identical, regardless of the case of each letter? If so, how?

Question 3

How would you use the Math class to square an integer?

Question 4

How would you use the Math class to take the square root of an integer?

Question 5

How do you take user input using JOptionPane?

Question 6

How do you display messages using JOptionPane?

Exercises

Exercise 1

Write a Java program which takes two integers as input (using JOptionPane.showInputDialog), and prints the smaller number. For example, if the numbers are 52 and 7, it should print the following:

7

Exercise 2

Write a Java program which takes one integer as input (using JOptionPane.showInputDialog), and prints out the value of 2 raised to the power of that number. For example, if you input 5, it should print the following:

32

Exercise 3

Write a Java program which takes two integers as input (assume that the first number is smaller than the second one). Then generate and print a random number which is between the two numbers you input. For example, if you give it the numbers 6 and 14, it should generate a random number between 6 and 14 inclusive.

Solutions

Question 1

Use the String class' .equals() method.

Question 2

Yes, using the String class' .equalsIgnoreCase() method.

Question 3

Use Math.pow(). The first argument is the number you are squaring, and the second parameter is 2.

Question 4

Use Math.sqrt().

Question 5

Use JOptionPane.showInputDialog().

Question 6

Use JOptionPane.showMessageDialog().

Exercise 1

import javax.swing.JOptionPane;

public class Test
{
	public static void main(String[] args)
	{
		String input; // User's input
		int first; // First input number
		int second; // Second input number
		int min; // Min of first and second

		// Get user input and put it into an integer
		input = JOptionPane.showInputDialog("Please input the first number");
		first = Integer.parseInt(input);

		// Get user input and put it into another integer
		input = JOptionPane.showInputDialog("Please input the second number");
		second = Integer.parseInt(input);

		// Get the smaller of the two numbers
		min = Math.min(first, second);

		// Print out the result
		System.out.println(min);

		// End the program
		System.exit(0);
	}
}

Exercise 2

Exercise 3