Improved Program

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:

It would be nice if the user could say how many terms to sum up.

Improved Program

The user might want to see the sum of the first 10 terms, for example:

1/1 + 1/2 + 1/3 + 1/4 +  1/5 +  1/6 +  1/7 +  1/8 +  1/9 +  1/10 

Here is the program again, with new blanks for the improvements. Now the number of terms to sum up (e.g., 10) is a parameter for the value() method:

import java.util.Scanner ;
class HarmonicSeries
{
  double value( int  )
  {
    int term=1 ;
    double sum = 0.0;
    
    while ( term <=  )
    {
      sum += 1.0/term;           // add the next term to sum
      term++ ;                   // increment term
    }

    return sum;
  } 
}

class HarmonicTester
{
  public static void main ( String[] args ) 
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("How many Terms? ");
    int limit = scan.nextInt();
    HarmonicSeries series = new HarmonicSeries();

    System.out.println("Sum of " + limit + " terms:" + series.value( limit ) );

  }
}

QUESTION 12:

Fill in the blanks to complete the program.