Java help request

Jun 18, 2004
101
0
0
Geez, I hate this self-teaching book. Can someone show me how to do the following problems in Java and also recommend a good self-teaching book that actually explains the concepts with a lot of examples. Thx.

1. The population of Mexico in 1990 as 89.2 million. Write a program that calculates and prints out the year in which the population of Mexico will reach 120 million, assuming a constant growth rate of 2.3% per year. Use a While loop to accomplish this task.

2. Write a program with a method int addOdds(int n) that calculates and returns the sum of all odd integers from 1 to n. Your method should use exactly one ?for? loop and no other iterative statements. (Do not use the formula for the sum of odd numbers).
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
import java.io.*;

public class PopulationApp{
...public static void main(String[] args){
......float fPopulation = 89200000;
......int numYears = 0, year = 1990;
......while (fPopulation < 120000000){
.........fPopulation *= 1.023;
.........numYears++;
......}
......year += numYears;
......System.out.println("Mexico will reach 120 million people in " + year);
...}
}
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
public class AddOdds{
...public int addOdds(int n){
......int i, sum = 0;
......for (i = 1; i <= n; i = i + 2){
.........sum += i;
......}
......return sum;
...}
}
 
Jun 18, 2004
101
0
0
I think I may have picked a book that is designed for people with a bit of background in Java programming. Are Sun?s tutorials good for complete newbies.

WOW! It only took you like a couple minutes to figure out the answer and I was working on those problems for nearly four hours before I gave up.


Thank you very much, sir.
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
Yes, the Sun tutorials are pretty basic. They may assume that you have some knowledge about basic programming in general, but no prior Java-specific knowledge is assumed.