Requirement 1) Modify the code to find and print sum of the same series from 1/2 through 1/n multiple times, where each n is read from data file. Requires nested loop with the inner loop summing up series and outer loop allow inner code to repeat once for each n read in from file. Loop until file EOF is reached.

Requirement 2) Modify the modified code. Write a 2nd method for class called summation. This method, which will be called by your main method, will receive the value of n from main, will sum from 1/2 through 1/n and will return the answer to main. Function header for new function: public static double summation (int n). Body of summation method will contain statements to do summation moved from main. Either have main method or summation print summation terms, but main must be one to print the answer returned to it by summation method.

Thanks in advance

My Code so far...

import java.io.*;
import java.util.Scanner;

public class Lab5A{
    public static void main(String[] args) throws FileNotFoundException
    {
            File inputFile = new File("Series2.dat");
            Scanner file = new Scanner(inputFile);
        
       int maxDen=file.nextInt();
        int den;
        double sum = 0;
        
       System.out.print("The summation of the series " );

        for (den=2; den<=maxDen; den*=2)
        {
            System.out.print("1/" + den);
            if (den < maxDen)
                     System.out.print(" + ");
            else System.out.print(" = ");
        
           // Get the sum so far.
        sum = sum + (1.0/den);
        }
        System.out.print(sum);
        
    
    }

}

Dani AI

Generated

Short answer: put the summation loop into a separate method that returns a double, and have main read each n from the file (outer loop) and call that method for each n (inner logic lives in the method). As suggested, you need a loop that reads every n; as discovered, earlier BufferedReader code failed because arithmetic was attempted on a String and integer division was used (both common pitfalls).

Example (minimal, focused on the required method and how main uses it):

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Lab5Refactored {
    public static void main(String[] args) throws FileNotFoundException {
        try (Scanner sc = new Scanner(new File("Series2.dat"))) {
            while (sc.hasNextInt()) {
                int n = sc.nextInt();
                System.out.print("The summation of the series ");
                for (int d = 2; d <= n; d *= 2) {
                    System.out.print("1/" + d + (d < n ? " + " : " = "));
                }
                double sum = summation(n);          // main must print the returned answer
                System.out.println(sum);
            }
        }
    }

    public static double summation(int n) {
        double sum = 0.0;
        for (int d = 2; d <= n; d *= 2) sum += 1.0 / d;  // use 1.0 to force floating division
        return sum;
    }
}

Troubleshooting notes drawn from the thread:

  • If you used BufferedReader, convert the read line with Integer.parseInt(...) before doing arithmetic.
  • Never do 1/den with den as an int (that does integer division); use 1.0/den or cast.
  • Use hasNextInt() before nextInt() to avoid InputMismatchException.
  • Keep the accumulator local to the method (or reset it every iteration) so sums don’t carry between different n values.
  • Guard against n < 2 (either skip or print a message) and be aware that d *= 2 can overflow for very large n.

This approach satisfies Requirement 2: public static double summation(int n) returns the computed value while main handles file input and printing.

What is the output you are getting ? Tell us where exactly are you facing problem.

This is my output that I do get: The summation of the series 1/2 + 1/4 + 1/8 + 1/16 = 0.9375. But when I make the required modifications, it doesn't run at all.

That is because this code does not read each n from the file, it just reads once from the file and sets it to maxDen thats it. You would require to read n and set it to maxDen every time so that it would require another for / while / do-while loop. Thats what the assignment statement reads

Requires nested loop with the inner loop summing up series and outer loop allow inner code to repeat once for each n read in from file

My recent modification:

import java.io.*;

public class lab5scrap{
    public static void main(String[] args) throws IOException {
        double sum; //Accumulator
        String den; //Hold value read from value

        //Open file
        FileReader freader = new FileReader("Series2.dat");
        BufferedReader inputFile = new BufferedReader(freader);

        //Initialize accumulator
        sum = 0.0;

        //Read first input from file
        den = inputFile.readLine();

        //If 1st line was successfully read,
        //convert to double/add to accumulator/read remaining numbers
        while (den != null)
        {
            //Convert string referenced by str to double
            //add to sum
            sum = sum + (1/den);

            //Read next line from file
            den = inputFile.readLine();
        }
        //Close file
        inputFile.close();
        //Display sum of numbers
        System.out.println("The summation of the series from 1/2 to 1/n is");
    }
}

recent modification:

import java.io.*;
import java.util.Scanner;

public class lab5scrap{

    public static void main(String[] args) throws FileNotFoundException
    {
            File inputFile = new File("Series2.dat");
            Scanner file = new Scanner(inputFile);

       
       while(file.hasNext()){
      int maxDen=file.nextInt();

        
       double sum = 0.0;

       System.out.print("The summation of the series " );

         for (int den=2; den<=maxDen; den*=2)
        {
            System.out.print("1/" + den);
            if (den < maxDen)
                     System.out.print(" + ");
            else System.out.print(" = ");

        // Get the sum so far.
        sum = sum + (1.0/den);
        }

        System.out.print(sum);
        }

    }

}

i get an error message even though no apparent errors in code

i was able to get the code to work. My problem now is how do I write a second method that returns to answer to main?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.