Java as a Calculator

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

No—bugs are not allowed in restaurants, nor in programs.

Java as a Calculator

All of the familiar mathematical functions that are found on an electronic calculator such as sine, log, and square root are available to your program in the Java Math class. Typically these functions expect data type double as an actual parameter and return a double value.

Here is a program that reads in a floating point number from the keyboard and prints out its square root:

import java.util.Scanner;

class SquareRoot
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner( System.in );
    double value;

    // read in a double
    System.out.print  ("Enter a double:");
    value = scan.nextDouble();
    
    // calculate its square root
    double result = Math.sqrt( value );
    
    // write out the result
    System.out.println("square root: " + result );
  }
}

The assignment statement (in blue) uses the sqrt() method of the class Math. This is a static method, which means that you ask for it using the name of a class and a dot operator, like this:

Class . method ( parameters )

This looks the same as calling a method of an object, but here a class name is used, not an object name.

QUESTION 12:

The class Math also has a log method that returns the natural logarithm of its argument. Mentally modify the program so that it returns the log of the input value.