Java: Can't figure out why I have an endless while loop

Discuss how to write good code, break bad code, your current pet projects, or the best way to approach novel problems

Java: Can't figure out why I have an endless while loop

Post by Amidda1217 on Tue Jul 27, 2010 7:22 am
([msg=42813]see Java: Can't figure out why I have an endless while loop[/msg])

I have been trying to figure this out and its a little frustrating. You guys have been awesome so far and have found my problems quickly. Hopefully you can help again. I have two classes one that contains methods that im invoking from my main. The while loop is supposed to calculate when one population of a species will outgrow another, but it just keeps counting.

Code: Select all
package pg331num1;
import java.util.Scanner;

public class Main {
     


    public static void main(String[] args) {
       
       
       int big, little;
       
       
       int years = 0;

       Scanner keyboard = new Scanner(System.in);
       Species newSpecies1 = new Species();
       Species newSpecies2 = new Species();
       Species largest = new Species();
       Species smallest = new Species();

       System.out.println("This program will calculate the amount of years \n"  //intro
               + "for a smaller population to outnumber a larger population");
       System.out.println("Lets start with the first species...");
       newSpecies1.readInput();                                                 //get input first species
       System.out.println("The information you entered is ...");
       newSpecies1.writeOutput();                                               //Display First Species


       System.out.println("Now, Lets gather information on the second species...");//gt input second species
       newSpecies2.readInput();
       System.out.println("The information you entered is ...");                //Display second species
       newSpecies2.writeOutput();


       if (newSpecies1.equals(newSpecies2)){                                    //Check to make sure species are not equal
           System.out.println("The two species are identical.");
        }
         


else if (newSpecies1.getGrowthRate() == newSpecies2.getGrowthRate()){
          System.out.println("Neither Species will ever outgrow each other.");
         
            //System.out.println("Error 1");
            return;
}



       else if((newSpecies1.getPopulation() > newSpecies2.getPopulation())
        && (newSpecies1.getGrowthRate() > newSpecies2.getGrowthRate()))
        {          //Checks to see which species is larger
            largest = newSpecies1;
            smallest = newSpecies2;
            System.out.println(newSpecies2.getName() + " will never out grow " + newSpecies1.getName());
            //System.out.println("Error 2");
            return;
       }
           
       
       else if ((newSpecies2.getPopulation() > newSpecies1.getPopulation())&&
               (newSpecies2.getGrowthRate() > newSpecies1.getGrowthRate()))
            {
                largest = newSpecies2;
                smallest = newSpecies1;
                System.out.println(newSpecies1.getName() + " will never out grow " + newSpecies2.getName());
                //System.out.println("Error 3");
                return;
            }
       else if((newSpecies1.getPopulation() < newSpecies2.getPopulation())
        && (newSpecies1.getGrowthRate() > newSpecies2.getGrowthRate()))
        {          //Checks to see which species is larger
            largest = newSpecies2;
            smallest = newSpecies1;
            //System.out.println("error4");
            }
       else if((newSpecies2.getPopulation() < newSpecies1.getPopulation())
        && (newSpecies2.getGrowthRate() > newSpecies1.getGrowthRate()))
        {          //Checks to see which species is larger
            largest = newSpecies1;
            smallest = newSpecies2;
            //System.out.println("error5");
            }
else if ((newSpecies2.getPopulation() == newSpecies1.getPopulation())
        && (newSpecies1.getGrowthRate() > newSpecies2.getGrowthRate()))
        {          //Checks to see which species is larger
            largest = newSpecies2;
            smallest = newSpecies1;
            //System.out.println("error6");
            }
       else if ((newSpecies2.getPopulation() == newSpecies1.getPopulation())
        && (newSpecies1.getGrowthRate() < newSpecies2.getGrowthRate()))
        {          //Checks to see which species is larger
            largest = newSpecies1;
            smallest = newSpecies2;
            //System.out.println("error7");
            }
big = largest.getPopulation();
little = smallest.getPopulation();

      while (big >= little){
            big = largest.predictPopulation(years);
           little =  smallest.predictPopulation(years);
           //System.out.println("error8 " + years);
           System.out.println(big);
           System.out.println(little);
            if (little > big){
                    System.out.println("The species " + smallest.getName() + " will outgrow "
                    + largest.getName() + " in " + years + " years.");}
                    years++;
//System.out.println(smallest.predictPopulation(10));
   
   
        }

       }
       
           
       }



Code: Select all
package pg331num1;

import java.util.Scanner;

/**
Class for data on endangered species.
*/
public class Species
{
    private String name;
    private int population;
    private double growthRate;

    public void readInput( )
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("What is the species' name?");
        name = keyboard.nextLine( );

        System.out.println(
                      "What is the population of the species?");
        population = keyboard.nextInt( );
        while (population < 0)
        {
            System.out.println("Population cannot be negative.");
            System.out.println("Reenter population:");
            population = keyboard.nextInt( );
        }

        System.out.println("Enter growth rate (% increase per year):");
       growthRate = keyboard.nextDouble( );
    }

    public void writeOutput( )
    {
         System.out.println("Name = " + name);
         System.out.println("Population = " + population);
         System.out.println("Growth rate = " + growthRate + "%");
    }

    /**
     Precondition: years is a nonnegative number.
     Returns the projected population of the calling object
     after the specified number of years.
    */
    public int predictPopulation(int years)
    {
      int result = 0;
        double populationAmount = population;
        int count = years;
        while ((count > 0) && (populationAmount > 0))
        {
            populationAmount = (populationAmount +
                          (growthRate / 100) * populationAmount);
            count--;
        }
        if (populationAmount > 0)
            result = (int)populationAmount;

        return result;
    }

    public void setSpecies(String newName, int newPopulation,
                           double newGrowthRate)
    {
        name = newName;
        if (newPopulation >= 0)
            population = newPopulation;
        else
        {
            System.out.println("ERROR: using a negative population.");
            System.exit(0);
        }
        growthRate = newGrowthRate;
    }

    public String getName( )
    {
        return name;
    }

    public int getPopulation( )
    {
        return population;
    }

    public double getGrowthRate( )
    {
        return growthRate;
    }

    public boolean equals(Species otherObject)
    {
        return (name.equalsIgnoreCase(otherObject.name)) &&
               (population == otherObject.population) &&
               (growthRate == otherObject.growthRate);
    }
}


Thanks a ton guys. I hope you can help me. Is it normal for people to have so much trouble when they are first learning to program? Or am I just an idiot? It seems like I am running into a lot of "should be simple" problems.


EDIT: I figured out the endless loop. Two operators were backwards. It was bad logic on my part. Now I need to figure out why when it runs it adds an extra year to the calculation. Is that something i fix by subtracting 1? or would that make other variations untrue.

EDIT 2: I got it. Thanks guys. No more programming for me when I have stayed up so late. I found a ton of problems.... lol
Last edited by Amidda1217 on Tue Jul 27, 2010 8:04 am, edited 1 time in total.
The user can't be patched.
Amidda1217
New User
New User
 
Posts: 31
Joined: Thu Jun 04, 2009 6:49 am
Blog: View Blog (0)


Re: Java: Can't figure out why I have an endless while loop

Post by neuromanta on Tue Jul 27, 2010 7:46 am
([msg=42815]see Re: Java: Can't figure out why I have an endless while loop[/msg])

I don't say that I see through your code completely, but my intuition is that you use a pre-testing loop where you shouldn't. I think if you would use a post-testing loop (like do-while) to test the condition, it would help. Try it out.
User avatar
neuromanta
Poster
Poster
 
Posts: 302
Joined: Mon Nov 30, 2009 9:29 am
Location: Hungary
Blog: View Blog (0)


Re: Java: Can't figure out why I have an endless while loop

Post by splargle on Tue Jul 27, 2010 7:47 am
([msg=42816]see Re: Java: Can't figure out why I have an endless while loop[/msg])

You have "years++;" before you do the check & print the result.
splargle
New User
New User
 
Posts: 1
Joined: Tue Jul 27, 2010 7:32 am
Blog: View Blog (0)


Re: Java: Can't figure out why I have an endless while loop

Post by Amidda1217 on Tue Jul 27, 2010 8:04 am
([msg=42819]see Re: Java: Can't figure out why I have an endless while loop[/msg])

thanks guys, I put the year++; after the if statement and fixed a ton of other problems.
The user can't be patched.
Amidda1217
New User
New User
 
Posts: 31
Joined: Thu Jun 04, 2009 6:49 am
Blog: View Blog (0)


Re: Java: Can't figure out why I have an endless while loop

Post by TheMindRapist on Tue Jul 27, 2010 1:28 pm
([msg=42837]see Re: Java: Can't figure out why I have an endless while loop[/msg])

Not sure if you know this, but a simpler method to predict population would be:

Code: Select all
public int predictPopulation(int years)
{
    return (int)(Math.pow((1+(growthRate/100)), years)*population);
}


Edit: Actually, a few other things. If the growth rates are the same you output that neither will outgrow each other. This is somewhat true, however unless the initial populations are the same one population will always be larger, and in some sense the larger species will outgrow the smaller species, due to the extra initial population being compounded. For the conditions where the initial population is equal but the growth rates aren't you can simply output that the species with the larger growth rate will outgrow the other species in one year (or one unit_of_time_here).
Image
User avatar
TheMindRapist
Contributor
Contributor
 
Posts: 585
Joined: Mon Apr 14, 2008 4:57 pm
Blog: View Blog (0)



Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests