Solutions to other chapters:
Java Methods A & AB:
Object-Oriented Programming and Data Structures
Answers and Solutions to Exercises
Chapter 8
1. |
|
public class Population
{
private final double growthRate = 1.017; // 1.7% increase per year
public static void main(String[] args)
{
double population = 106.2, target = 120.0;
int year = 2005;
while (population < target)
{
population *= growthRate;
year++;
}
System.out.println("The population will reach " + target
+ " million in " + year);
}
} |
3. |
|
public static int addOdds(int n)
{
int sum = 0;
for (int i = 1; i < n; i += 2)
sum += i;
return sum;
} |
5. |
|
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int sum = 0;
System.out.print("Enter a positive integer under 10: ");
int n = input.nextInt();
for (int i = 1; i <= n; i++)
{
if (i > 1)
System.out.print(" + ");
System.out.print(i);
sum += i;
}
System.out.println(" = " + sum);
} |
6. |
(a) |
public static boolean isPrime(int n)
{
if (n < 3)
return n == 2;
else if (n % 2 == 0)
return false;
int m = 3;
while (m * m <= n)
{
if (n % m == 0)
return false;
m += 2;
}
return true;
} |
|
(b) |
public static boolean isPrime(int n)
{
if (n < 5)
return n == 2 || n == 3;
else if (n % 2 == 0 || n % 3 == 0)
return false;
int m = 5;
while (m * m <= n)
{
if (n % m == 0 || n % (m + 2) == 0)
return false;
m += 6;
}
return true;
} |
7. |
|
public static boolean isPerfectSquare(int n)
{
int p = 1, sum = 0;
while (sum < n)
{
sum += p;
p += 2;
}
return sum == n;
} |
|