0% found this document useful (0 votes)
5 views

Java project

This Java program calculates the sum of the first 'n' terms of a mathematical series using user input. It employs JOptionPane for input and handles invalid entries with error messages. The result is formatted to four decimal places and displayed in the console.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java project

This Java program calculates the sum of the first 'n' terms of a mathematical series using user input. It employs JOptionPane for input and handles invalid entries with error messages. The result is formatted to four decimal places and displayed in the console.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import javax.swing.

JOptionPane;
import java.text.DecimalFormat;

public class series {


public static void main(String[] args) {
int n = 0;

// Input from user using JOptionPane


String input = JOptionPane.showInputDialog(null, "Enter the number of terms
(n):");

if (input == null) System.exit(0); // User cancelled

try {
n = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
System.exit(0);
}

int count = 1;
double sum = 1.0;
int sign = -1;
int denominator = 3;

// Start loop
while (count < n) {
sum += sign * (1.0 / denominator);
sign *= -1;
denominator += 2;
count++;
}

double result = 4 * sum;


DecimalFormat df = new DecimalFormat("0.0000");
String formattedResult = df.format(result);

// Display result
System.out.println("Sum of the first " + n + " terms is: " + formattedResult);
}
}

You might also like