Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Java application for infinite series that calculates pi

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java application for infinite series that calculates pi

    Hi

    I am having trouble compiling my code for a java application that is supposed to print out the infinite series for Pi. Here is my java code:

    //a java application that generates the infinite series for Pi, ie 3.14159...=4-4/3+4/5-4/7+4/9
     
    public class Pi{
     
    	public static void main(String args[]){
     
    //declare and initialize variables
     
    long counter=1;
    double pi;
     
     
    double total=0;
     
    for(counter=1; counter<=1000; counter++)
     
    pi=4+4*(Math.pow(-1,counter))/(2*counter+1);
     
     
     
    total=total+pi;
     
    System.out.printf("Infinite series for Pi is %f", total);
     
    }//end main
     
    }//end class

    Here is the error in my output that results when I attempt to compile my code:

    C:\Users\anonymous\Desktop\chapter five exercises for java\Pi.java:21: error: variable pi might not have been initialized
    total=total+pi;
    ^
    1 error

    Tool completed with exit code 1
    Why do I need to initialized pi when I already initialized the total?


  2. #2
    Member Ada Lovelace's Avatar
    Join Date
    May 2014
    Location
    South England UK
    Posts
    414
    My Mood
    Angelic
    Thanks
    27
    Thanked 61 Times in 55 Posts

    Default Re: Java application for infinite series that calculates pi

    Because double is a primitive type - and is assigned null by default.
    Therefore - when you attempt to use the variable in the assignment statement,
    the compiler does not know what pi was initialized to before the statement.
    Assign pi a base value.

    Wishes Ada xx
    If to Err is human - then programmers are most human of us all.
    "The Analytical Engine offers a new, a vast, and a powerful language . . .
    for the purposes of mankind
    ."
    Augusta Ada Byron, Lady Lovelace (1851)

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Java application for infinite series that calculates pi

    Because double is a primitive type - and is assigned null by default.
    Not sure I understand (or agree with) this statement.

    The compiler complains because it requires variables to be initialized by default. It is called Definite Assignment, outlined in more detail in the JRE Spec

  4. #4
    Junior Member
    Join Date
    Apr 2014
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java application for infinite series that calculates pi

    Nevermind , problem solved

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java application for infinite series that calculates pi

    I also don't agree. class level variables don't need to be initialized. Variables in a method must be initialized.
    double is a primitive and when defined at the class level is given a default value of 0.0
    For example. Some code from the middle of my test program:
    class TestCode18 {
       double xxxx;
       public TestCode18() {
                System.out.println("xxxx="+xxxx);  // xxxx=0.0
       }
     
       public static void main(String[] theArgs) throws Exception {
          new TestCode18();
       }
    }
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Jul 2013
    Posts
    8
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default

    You should always initialise variables with a value. If they're not given a value, they get assigned null.

  7. #7
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Java application for infinite series that calculates pi

    Quote Originally Posted by CDeighan View Post
    You should always initialise variables with a value. If they're not given a value, they get assigned null.
    This is not true for primitives, and only true for class variables. See Norm's answer.

    And, actually, you should /not/ always explicitly assigned class variables, primitives or objects. Many compilers actually do (or did -- you'd have to look at the bytecode) not optimize the unneeded assigment to 0 or null away. That is, they emit larger code for the class.

    Of course, in this case, the class variable does need to be assigned to some default prior to be used on the right-hand side of an assignment, because the compiler can't be sure it was assigned something in the loop.

    In many cases lke this I will show the assignment to a default directly above the condition that will probably change it, so the state of the property is determined in the same chunk of code.

  8. #8
    Member Ada Lovelace's Avatar
    Join Date
    May 2014
    Location
    South England UK
    Posts
    414
    My Mood
    Angelic
    Thanks
    27
    Thanked 61 Times in 55 Posts

    Default Re: Java application for infinite series that calculates pi

    Interesting topic - and thank you everyone for their insights. Can I apologise for
    my mistake in my previous answer, I think I got class-type and primitive's a bit
    muddled

    On this note - to prevent such an error, would it be feasible to, instead of doing this:

    double x;

    Do this:

    double x = input.nextDouble()

    Would this prevent such a problem in such a trivial case? The actual
    assignment is being done as at declaration time (think this was mentioned
    above) - just a query that's all.

    Wishes Ada xx
    If to Err is human - then programmers are most human of us all.
    "The Analytical Engine offers a new, a vast, and a powerful language . . .
    for the purposes of mankind
    ."
    Augusta Ada Byron, Lady Lovelace (1851)

  9. #9
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Java application for infinite series that calculates pi

    In general, the only reason to have declared but uninitialized class variables is if they are also class properties. In which case there will, or should, be setters, getters and or initializers in constructors.

    Otherwise, declare and, if necessary, initialize them as needed. This isn't C, so don't bother with declaring plain old variables up front. Of course, when doing toy apps like this, with everything in main(), the line between class variables, locals and properties is blurred. Java, unlike C#, doesn't actually enforce this distinction, so it is up to the person between the keyboard and the chair to understand what they are doing.

Similar Threads

  1. [SOLVED] Java Coding: Assistance with a loop that calculates maximum, minimum, and average of 10 inputted numbers.
    By Knowledge_Feeds_The_Mind in forum What's Wrong With My Code?
    Replies: 20
    Last Post: February 27th, 2014, 11:11 PM
  2. for loop that calculates the total of a series of numbers
    By JessicaCouture95 in forum Loops & Control Statements
    Replies: 8
    Last Post: November 3rd, 2013, 07:38 PM
  3. Replies: 2
    Last Post: September 27th, 2013, 04:20 AM
  4. Find a java program that calculates
    By Zuhairi Abdullah in forum Object Oriented Programming
    Replies: 3
    Last Post: May 9th, 2013, 11:08 AM
  5. java code for fibonacci series?
    By javawreker in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 1st, 2012, 08:02 AM