Skip to main content

Section 3.8 Worked Example: Call a method of Scanner

Subgoals for Calling a Method.

  1. Classify method as static method or instance method
    1. If static, use the class name
    2. If instance, must have or create an instance
  2. Write (instance / class) dot method name and ( )
  3. Determine whether parameter(s) are appropriate
    1. Number of parameters passed must match method declaration
    2. Data types of parameters passed must match method declaration (or be assignable)
  4. Determine what the method will return (if anything: data type, void, print, change state of object) and where it will be stored (nowhere, somewhere)
  5. Evaluate right hand side of assignment (if there is one). Value is dependent on method’s purpose

Subsection 3.8.1

You can watch this video or read through the content below it.

Subsection 3.8.2 Problem Statement

Given the following code, how do you read in a double variable?
Scanner input = new Scanner(System.in);

Subsection 3.8.3 SG1: Classify method as static method or instance method

We already have an instance of Scanner with the variable name input.

Subsection 3.8.4 SG2: Write (instance / class) dot method name and ( )

First, check the API to find a method that does what we want.
Figure 3.8.1.
input.nextDouble()

Subsection 3.8.5 SG3: Determine whether parameter(s) are appropriate

No parameters required (again check the API)

Subsection 3.8.6 SG4: Determine what the method will return (if anything: data type, void, print, change state of object) and where it will be stored (nowhere, somewhere)

According to the API documentation, the nextDouble method returns a double, so we need a double type variable to store the value.
double value = input.nextDouble();

Subsection 3.8.7 SG5: Evaluate right hand side (RHS) of assignment (if there is one). Value is dependent on method’s purpose

According to the API documentation, the nextDouble method reads the next value from the input stream and attempts to convert it into a decimal value.
double value = input.nextDouble();

Practice Pages.

You have attempted of activities on this page.