Calculating Pi In While Or Do While Loop

Oct 23, 2014

USING A WHILE OR A DO-WHILE LOOP write a program to compute PI using the following equation:

PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...

Allow the user to specify the number of terms (5 terms are shown) to use in the computation. Each time around the loop only one extra term should be added to the estimate for PI.

Alter your solution from part one so that the user is allowed to specify the precision required between 1 and 8 digits (i.e. the number of digits which are correct; e.g. to 5 digits PI is 3.14159), rather than the number of terms. The condition on the loop should be altered so that it continues until the required precision is obtained. Note that you need only submit this second version of the program (assuming you have it working).

View Replies


ADVERTISEMENT

Why Is It Not Calculating The Total After Leaving The Loop

Feb 27, 2015

i want it to calculate my earnings say for 4 months and then output the result. it runs the loop asking for the 4 months worth of earnings but then it shows just the amount entered for the month and not total.

package Earnings;
 import java.util.Scanner;
import java.lang.Math;
public class Earnings {
public static void main(String[] args) {

[code]....

i tried changing from double month to String month but it doesn't work.

View Replies View Related

Adding Fractions - Loop For Calculating Total Of Series Of Numbers

Mar 8, 2014

I'm just not noticing why it won't display the answer. I'm trying to solve this book problem......

"Write a for loop that calculates the total of the follower series of numbers:

1/30 + 2/29 + 3/28......+30/1"

Here is what I have..

public static void main(String[] args) {
double total = 0;
for (double a = 1, b = 30; b < 1; a++, b--) {
total += (a / b);
}
System.out.println(total);
}
}

When launched, the output is 0.0. I tried changing the variables a and b to doubles but didn't change anything...

View Replies View Related

Calculating Sin(x) Without Using Math

Sep 14, 2014

I'm trying to calculate sin(x) without using Math.sin(x). The formula for sin(x) is: x - x^3/3! + x^5/5! ... I can't seem to get the coding for the alternating +/- right. Here's my program:

import java.util.Scanner;
import java.lang.Math;
class Sin
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n, c, fact = 1, count = 1;
double x, sum = 0, sum_sin = 0, result;

[Code] ....

View Replies View Related

Calculating Factorial Of Int Number

Mar 2, 2014

I'm working on some exercises and I'm having some problems with a method. I want to create a method to calculate the Factorial of an int number. I already wrote code that asks the user to input an int number and it calculates the Factorial, and it works fine

i.e.: if I input 5 it outputs

5! = 120

as it should. Here's the code:

import java.util.Scanner;
public class Factorial1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int total = 1;
 
[Code] ....

Now I want to make a method to re-use this code in other programs and I wrote this program:

public class TestClass {
public static void main(String[] args) {
System.out.print(factorial(5));
}
  public static int factorial(int x) {
int total = 0;

[Code] ....

But when I run this program it outputs 0 instead of 120. What is wrong with this code as it compiles just fine but doesn't work as intended.

View Replies View Related

Calculating Factorials Using BlueJ

Oct 7, 2014

I am trying to calculate factorials using BlueJ. All of my factorials calculate correctly, I am just having an issue with something the instructor asked of us. She asked us to force the loop to stop when the user inputs "Calculate the factorial of 0", and not give any print.

So far I have my for loop with the correct conditions, I am just really confused as to how to make an if statement to stop the code when the input is 0.

View Replies View Related

Calculating Average Of Values

Apr 21, 2014

I'm struggling with this assignment I was given:

Given list of positive integer values, write a program to calculate average of the values. List terminates with -1.

View Replies View Related

Calculating FPS - Delta Variable

May 26, 2014

I am working on the first example in this java game programming book. I am having trouble understanding this basic concept. How does the delta variable work throughout this class? I know the syntax I just don't understand the concept fully.

Explain these components of the program:

1) delta += current-lastTime works
2) lastTime = current;
3) if(delta > 1000)
{
delta-1000
....
}

package javagames.util;
public class FrameRate {
private String frameRate;
private long lastTime;
private long delta;
private int frameCount;

[Code] .....

View Replies View Related

Calculating Total Payout

Jun 5, 2014

what I'm missing to calculate the Total Payout that Payroll has given out to two employees. the professor states that we have to use "getTotalPayout" . It would have been easy to do "(employee1.getFinal() + employee2.getFinal())" but he use getTotalPayout.

public class Payroll
{
private String employeeId;
private int hourlyrate, hoursworked;
private int increaseHours = 10;
private double TotalPayout;

[code]....

View Replies View Related

Calculating Area With JOptionPane?

Sep 9, 2014

I am supposed to be doing a class assignment that calculates the area of a triangle and outputs with JOptionPane. I was able to fix some errors, but it's uncovering more errors.Here is my code:

import javax.swing.JOptionPane;
import java.util.*;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

public class Area {
public static void main (String [] args) {
double a, b, c; //Input sides of triangle
double x; //Perimeter of triangle
double area; //Area of triangle
StringTokenizer st;

[code]....

View Replies View Related

Calculating Years Between Two Dates?

Feb 24, 2014

write a program that reads in the year, month, and day of a couple's wedding date and compute thier next wedding anniversary after March 2, 2011.

TThis has to be input in a message dialog box also.

View Replies View Related

HashCode For Calculating Different Objects

Jun 22, 2014

I'm trying to make a method that creates objects of a parameterized type randomly, but also to store the hashCode of different objects created and if at any time the percentage of different objects is less than 50% throw an exception.

This last part is where I've gotten stuck. I have created a population property where I store the different hashCodes and update it in the method adding the new hashCode from the new object. But I don't know how to do for to know if the percentage of different objects is less than 50%.

package fp.tipos.apps;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
public class FactoriaApps {
 
[Code] .....

View Replies View Related

Calculating Sum Of Elements Within JList

Mar 25, 2015

I'm currently in the process of creating a shopping cart simulation. The main GUI consists of two lists, one is a list of the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.

Below is the method for my scan button, which is supposed to perform the above :

public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;

[code]...

View Replies View Related

Java Calculating Mean Average

Feb 21, 2014

I am trying to do the following java assignment and every thing seems to work fine except when I put a number<4 or >10 it prints both "Invalid grade!"

"You didn't enter any data!" what I wanted is to print only "Invalid grade!" I tried to fix it but I couldn't.

Create a program that asks for results of exams and calculates the mean average of the grades. Grades are floating point numbers between 4 and 10. Program asks for grades until a negative number is typed. If user gives a grade other than a number between 4 and 10, the text "Invalid grade!" will be printed on screen and program asks for another grade. Finally the program prints the number of inputted grades and their mean average on screen as shown in the example print. If no grades were inputted, the notice "You did not input any grades." is the only thing printed on screen.

A double type variable is to be used to store the value of the average.

Program is written to a class called Average.

Example output

Program calculates the average of inputted grades.

Finish with a negative integer.

Input a grade (4-10): 5
Input a grade (4-10): 6,5
Input a grade (4-10): 7,5
Input a grade (4-10): 7
Input a grade (4-10): 0
Invalid grade!
Input a grade (4-10): -4
4 grades inputted.
Average of the grades: 6.5

Java Code:

import java.util.Scanner;
public class apples {
public static void main(String[] args)
int inputNumber=0;
int sum;
int count;
double average;

[Code] .....

View Replies View Related

Calculating Area And Circumference Of A Circle

Apr 21, 2014

Here is the code that I wrote out:

//program that calculates the circumference and area of a circle

import java.util.Scanner;
public class circle{
public static void main(String[] args){
Scanner input= new Scanner( System.in);
double r; //declares radius

[Code] .....

And here is what is displayed in the command prompt when I compile my code:

circle.java:17: error: cannot find symbol
r.input.nextdouble();//entered the radius
symbol: method nextdouble()
location: variable input of type Scanner
1 error

What am I doing wrong?

View Replies View Related

Calculating Rainfall Quarterly Per Year

Mar 30, 2015

//calculates rainfall quarterly per year
 
import java.util.Scanner;
 public class SophiaKeyProgram2 {
 public static void main(String[] args) {
// TODO Auto-generated method stub
 
int numQuarter; //number of quarters in a year
double rainfall=0; //the amount of rain

[Code] ....

View Replies View Related

Calculating Points On A Circle Using Radius

Oct 24, 2014

I have to print points on a circle in increments of -0.1, but when I use a number larger than 1.3, the list stops at 0.1 larger than negRadius, and I don't know why. (Assume the center is (0,0))

public class PointsOnACircleV1
{
public static void main(String[] args)
{
double radius = 1;

[code]...

View Replies View Related

Swing/AWT/SWT :: Getting Numbers And Calculating Them In JTable

May 26, 2014

What I am trying to do on jtable is when a user enters values of numbers in the table, by click of button, those numbers are calculated and display in another column. For example, 4 = 2 + 2 in a table.This means getting inputs from user and summing them up. My getRowCount() and getValueAt() methods don't seem to work for me recently.

View Replies View Related

Calculating Number Through 4 Drop Down Menus

Jan 5, 2015

How to calculate an outcome/number through a combination of 4 drop down menus (drop down menu's 1 and 2 combine to form a specific value and menu's 3 and 4 combine to form a specific value), example ;

1st drop down menu (1*) = a,b,c,d,e
2nd drop down menu (2*) = 5,4,3,2,1
3rd drop down menu (3*)= a,b,c,d,e
4th drop down menu (4*)= 5,4,3,2,1

Example of drop down menu layout - [URL] ....

a->e = low to high (value) predominant value so b5>a1 ; d5>c1
5->1 = low to high (value)

Then the calculation involves the 1st and 2nd menu to form 1 value, so c3, e4 etc and the 3rd and 4th menu unite to form 1 value that is different from the first; c2, e3

So (1*2*) b3 ; (3*4*) b1 = x value

Also the value from 1*2* menu must be lower than value from menu 3*4*; so you cannot input 1*2* c4 ; 3*4* c5 /or b1 (so once the first menu is selected, the 3rd and 4th menu's wont show anything lower)...

View Replies View Related

Calculating Areas Of Geometric Shapes

Oct 21, 2014

Write a class that has three overloaded static methods for calculating the areas of the
following geometric shapes:

• circles -- area = π*radius^2 (format the answer to have two decimal places)
• rectangles -- area = width * length
• trapezoid -- area = (base1 + base2) * height/2

Because the three methods are to be overloaded, they should each have the same name , but different parameters (for example, the method to be used with circles should only take one parameter , the radius of the circle).

Demonstrate the methods in a program that prints out the following areas, each on a separate line:

• the area of a circle with radius 3
• the area of a rectangle with length 2 and width 4
• the area of a trapezoid with base lengths 3 and 5 and height 5

SAMPLE RUN #1
--- Prompts For Keyboard/Console/Standard Input ---
Inputs
Outputs
--- Monitor/Console/Standard Output ---
28.27
8.0
17.5

What The Console Looks Like In An Interactive Session:
(Note: this combines standard input with standard output )

>java Area
28.27
8.0
17.5

THIS IS MY CODE

import java.util.*;
public class Area {
public static double area(double radius)
{
return (double)(Math.PI*Math.pow(radius,2));
}
public static int area(int length, int breadth)

[Code] ....

View Replies View Related

Swing/AWT/SWT :: Calculating Time And Speed In Java GUI

Sep 27, 2014

So i'm using Netbeans and have created this template for the program i want to create. Basically what I want to do is enter a time and date in 24hr format including seconds and the date of start and end time and have the program calculate the time difference between Tool launch and tool Receive that takes into factor the Launch and Receive Dates for a total of hh:mm:ss duration. I don't know how to combine both those factors output one number in a total number of hours Duration. I'm also having problems linking the ODO (odometer) which the formula would basically be time/ODO (or distance in feet) = x.x ft/sec format.

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates and open the template in the editor.
*/

public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();

[Code] .....

View Replies View Related

Getting Wrong Values When Calculating Perimeter And Area?

Mar 22, 2015

I've been given a school assignment that reads, "Rewrite the main class Geometry so it takes in the dimensions for the triangle and ellipse as user inputs and create a Triangle and an Ellipse class. Use the appropriate variable types, constants, variable names and computational formulas.

Triangle class will have a computePerimeter and a computeArea methods Ellipse class will have a computeArea method Create Report class

• Create a method createReport that takes the values returned from Triangle and Ellipse and combines them in the following message and displays it. Format the values so that they have 2 decimals.

“The triangle has a perimeter of [perimeter] with an area of [area] while the ellipse has an area of [area]”

• Create a method switchReport that takes the original string from createReport and changes the message to display using the available methods in the String class

“The ellipse has an area of [area] while the triangle has an area of [area] with a perimeter of [perimeter]”"

I've run into a problem when creating the createReport method. Everytime i run it i get incorrect values for the perimeter and area (namely i get zero every time).

my code is as follows:

public class Triangle
{
public double base;
public double height;
public double hypotenuse;
private double tArea;
private double perimeter;
  public Triangle()
{
base = 0;
height = 0;
hypotenuse = 0;

[code]....

For the triangle class and

public class Report {
  Triangle tri2 = new Triangle();
Ellipse eli2 = new Ellipse();
  public Report() { 

public void createReport() {
System.out.println("The triangle has a perimeter of "+tri2.computePerimeter() +" with an area of " +tri2.computeTArea() +" while the ellipse has an area of " +eli2.computeEArea() );
}

for the report class.the Geometry class allows you to input values and if i skip the report and simply print the perimeter and area they are correct. However with the report class it simply gives me zeros.

View Replies View Related

Calculating Arithmetic Expression - Recursive Function

Oct 26, 2014

I have a given arithmetic expression, which form is (A+B) or (A-B), were A and B are either numbers from 0-9, or another ARITHMETIC Expression.

The first thing that comes to my mind is a recursive function, but how to start...

View Replies View Related

Program For Calculating Circumference And Area Not Working

Jul 15, 2014

Here is the program I wrote for calculating the circumference of a circle.

//circumference.java
//program that calculates the area and circumference of a circle
import java.util.Scanner; //program uses class scanner
public class circumference{
//main method begins execution of Java application
public static void main(String args[]){

[Code] .....

Even though my code compiles and runs without any errors, the program doesn't calculate the circumference.

View Replies View Related

Calculating Change In Denominations Of Currency Error

May 10, 2014

So I currently have working code that calculates the denominations that I need when change is displayed. The problem is that it seems to be missing one cents every time. So if my change prints out $12.35, it will end up being 1 - ten, 2 - ones, 1 - quarter, 1 - nickle, and 4 - pennies rather than 2 nickles. or 1 dime This happens for any dollar amount unless it is even cash and no change, or the change calculates to where there doesn't need to be a penny. Just an FYI, this code is being used in a GUI panel program if it seems strange in anyway.

int change1 = (int) ((total - realTotal)*100);
num100 = change1 / 10000;
change1 = change1 % 10000;
String dollar1;
dollar1 = String.valueOf(num100);

[code]....

View Replies View Related

Calculating Values And Passing From Two-dimensional Array

Jan 29, 2014

Long story short: The program takes user values (temperature) and converts them to the opposite (C >> F / F >> C)

I originally started this program with three separate arrays but then decided that it would be a good opportunity to use a two-dimensional array and one other.

The two-dimensional array has 2 rows, 10 columns. The second is a normal String array ...

Java Code:

String[][] myTemperatures = new String[2][9];
String inputAssembly[] = new String[9]; mh_sh_highlight_all('java');

I prompt the user for to enter temperature values, using a GUI and jbutton to distinguish F/C. Each time the user clicks 'continue', the values are stored into the two-dimensional array. One row holds the temperature, the other holds the C or F designation.

Java Code:

// CONTINUE BUTTON CLICK ACTIONS
class ContinueButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
input = view.getTempValue();

[Code] ....

This is where I am experiencing the trouble and I cannot seem to get the Debug to work properly here. When the two-dimensional array is full OR the user clicks 'calculate' instead of 'continue', the Calculate event is performed via an ActionListener.

Java Code:

// CALCULATE BUTTON CLICK ACTIONS
class CalculateButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String hold;
Double temp;

And I get a ton of errrors ...

Java Code:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "[Ljava.lang.String;@7441b1fd"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)

[Code] ....

I imagine the issue lies within how I am handling the two-dimensional array in the CALCULATE event and/or converting the String[][] to String then parsing to an Integer.

Would this be better done is separate arrays (not using one two-dimensional, but storing 34C, 45F ... in one. I think this would be difficult for me to parse for conversions).

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved