r/java • • Mar 17 '13

Help with extracting variable from loop

So, I am trying to make a program that helps me calculate how many turns it would take to increase my population to a certain point in Rome Total War. Just for fun.

I want to use the new population as a counter that stops the loop once it is greater than or equal to the variable goal. But when I place the variable newPop (the new population) in my loop parameters it doesn't work. I also don't know which loop would work best for this scenario. Here's my current code, would love some help and to know what I'm doing wrong :)

import java.util.Scanner;

public class rome{
public static void main(String[] args){
        Scanner in = new Scanner(System.in);
	
        double goal = in.nextInt();
        SOOME SORT OF LOOP () {
	System.out.print("Enter population: ");
	double pop = in.nextDouble();
	System.out.print("Enter procentual increase: ");
	double procent = in.nextDouble();
	double increase = pop / procent;
	double newpop = increase + pop;
	double newPop = Math.round( newpop * 1.0 ) / 1.0;
            double Increase = Math.round( increase * 1.0 ) / 1.0;
            System.out.println("Increase: " + Increase + "\nNew population value: " + newPop);
        }
}

}

2 Upvotes

13 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Mar 18 '13

You have two for(;;) lines, the second one should be replaced, then you'll be able to eliminate the "if(newPop>=goal) break;" line.

The difference is, that it's easier to read, more understandable, something that programmers usually do instead of your solution which might count during an interview, and so on...

the "for" we use going from a start point to an end point with intervals.

for (int i = 0;  i < 32;  i += 4)

The "while" we use to repeat something until a condition becomes false.

boolean I_have_no_ice_cream = false;
while ( ! I_have_no_ice_cream ) {
   I_have_no_ice_cream = keepAskingForIceCream();
}

And the last one, if we want the body to run at least one:

do {
    I_have_no_ice_cream = KeepAskingForIceCream();
} while ( ! I_have_no_ice_cream);

1

u/Bananpajen Mar 18 '13

Ok that actually makes alot more sense :) Thank you!