Program 1

We’d like to write a program that will project the growth of a University’s student population over the next 10 years. The following program asks the user to provide the current population and the rate of growth in percentages. As we assume that we can’t grow by a fractional number of people in any given year, the growth is calculated as an integer.

import java.util.Scanner;

public class PopCheck {

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("What is the current population? ");
    short pop = scan.nextShort();
    System.out.print("What is the rate of growth? (e.g., for 10% enter 10)");
    short growth = scan.nextShort();

    float growthRate = growth/100f;    //convert the growth rate to a float
    System.out.println("Year\tGrowth\tNew Population");
    for (int i = 1; i <= 10; i++)  {
      // calculate increase and new population
      // Force them both to be shorts
      short increase = (short) (pop * growthRate);
      short newpop = (short) (pop+increase);
      System.out.println(i+"\t"+increase+"\t"+newpop);
      pop = newpop;
    }
    System.err.println("Final population is "+pop);
  }
}
Security Checklist
Vulnerability: Integer Errors Course: CS2
Check each line of code Completed
1. Underline each occurrence of an integer variable.
For each underlined variable:
2. Mark with a V any input operations that assign values to the variable.
3. Mark with a V any mathematical operations involving the variable.
4. Mark with a V any assignments made to the variable.
Highlighted areas indicate vulnerabilities!
 
Copyright © Towson University