Files
GTSchoolShit/CS1322/p1/p1.nfo
2025-06-07 01:59:34 -04:00

391 lines
16 KiB
Plaintext

CS1322- Program 1 - The World as Arrays
=======================================
Assigned: Sunday, September 1st, 2002
Due: Monday, September 16th, 2002 at 11:59:59PM
Stop accepting: Tuesday, September 17th, 2002 at 08:00:00AM
Phase II Feedback deadline: Friday, September 6th, 2002 at 11:59:59PM
Phase IV Feedback deadline: Thursday, September 12th, 2002 at 11:59:59PM
TOPICS
==============================================================================
Topics you should understand coming into this assignment:
o The basic mechanics of java
o Basics of Objects and methods
Topics that you should understand as a result of doing this assignment:
o Object Creation and manipulation
o Iteration
o Arrays
o Multi-dimensional Arrays
o Testing and Debugging
o Arrays of Objects
PROGRAM WALKTHROUGH
==============================================================================
In this program, you will be managing a set of cities around the world.
You will be creating a data structure which will hold a map of several major
cities around the world. Their locations will be identified by latitude and
longitude(more on this later).
PHASE I - Building Citites
==============================================================================
Each City will have a name, country, population, and of course: a location.
We will be creating a class to hold all of this information for a city. Then,
we will creating many instance of this class (also known as objects) which
will represent real cities.
First, create a new class named City. This City should be public so that
any other class can see it. This City should have several pieces of data:
o A name(called "name") which will be represented as a String
o A country(called "country") which will also be represented as a String
o A population(called "population") will be represented as a number. Now,
the population of a country can be very, very large, so for now, we will
want to use a primitive integer type which can be larger than an int.
Figure out which type this is and declare the population variable of this
type.
Now, you are going to create a constructor for a City. A constructor is a
special type of method that is used to create a new City. The format for a
constructor is the same as a method, except that the name must be the name of
the class it is in, and there can be no return type. Create a constructor for
City that takes in a String which represents the name and sets the name of the
City to this new name. Remember that a constructor does not return anything.
Now, make another constructor for City that takes in nothing, and sets the
name to "Unknown".
As in the first assignment, you created accessors and modifiers, do that for
all of these variables now. Remember that the variables should be private and
the accessors and modifiers public.
Now, create a toString() method which will display the data for a City in the
following format:
City: <NAME>, <COUNTRY>: Population: <POPULATION>
examples: Albany, United States: Population: 1267326
Moscow, Russia: Population: 5234800
PHASE II - Iteration Practice (instant feedback phase)
==============================================================================
Eventually, we will need to go through all of the cities in the world to
perform certain operations. So, in this phase, we're going to practice
"looping" through things.
*******
*LOOPS*
*******
Most of the following can be found in lecture slides:
for loop
--------
Description: a loop used primarily to perform a block of code a certain fixed
number of times.
Example:
for(int i=0; i<10; i++) {
System.out.println("Now i is: "+i);
} //end for
while loop
----------
Description: a loop used to perform a block of code until some event occurs.
Example:
boolean userDidSomethingCool = false;
while(userDidSomethingCool == false) {
System.out.println("Not yet");
userDidSomethingCool = didUserDoCoolStuff();
} //end while
do while loop
-------------
Description: a loop which functions exactly like a while loop, but is
guaranteed to execute at least once
Example:
int choice;
int QUIT_CHOICE = 9;
do {
choice = getUserInputFromMenu();
handleChoice(choice);
} (while choice != QUIT_CHOICE);
Create a class named IterationTest (make sure it is public). In this class,
you are going to implement some methods that MUST USE ITERATION.
/**
* Prints the specified message the specified number of times.
* <BR>
* For example: printMessageALot("5 times!",5) would print
* 5 times!
* 5 times!
* 5 times!
* 5 times!
* 5 times!
* <BR><BR>
* @param message the message to print
* @param count the number of times to print the message
*/
public void printMessageALot(String message, int count) {
//YOUR CODE HERE
} //end printMessageALot(String,int)
/**
* Returns the first number raised to the power of the second number.
* <BR>
* For example: power(4,3) would return 4 * 4 * 4 = 64
* <BR><BR>
* @param base the number to raise to the power
* @param exponent the power to raise the base to (will always be greater
* then 0)
* @return the base raised to the exponent
*/
public int power(int base, int exponent) {
//YOUR CODE HERE
} //end power(int,int)
PHASE III - Fun with Arrays
==============================================================================
Now we will work with your first data structure in CS1322, the array. This
structure has already been built for you, all you need to do is use it. This
phase will get you accustomed to using arrays so that we may use them to
manage the recently-created Cities.
********
*ARRAYS*
********
Most of the following can be found in lecture slides:
Q: What is an array?
A: An array is a data structure that can hold a finite amount of data of the
same type. You declare how many elements the array can hold, what type of
data can go in it, and where. Arrays can be of any type.
Declaring an array
------------------
Here is the syntax(format) for declaring an array:
<TYPE>[] <NAME> or <TYPE> <NAME>[]
For example: int numbers[]; is the same as int[] numbers; Both create an
array of ints named numbers.
Setting the size
----------------
To set the size of an array, you can create a new array of the specified type
and pass the size in as an array parameter. See the following:
int numbers[] = new int[8];
This statement declares a new int array named numbers and gives it a size of
eight. This statement does the same thing:
int numbers[];
numbers = new int[8];
Filling up the array with data
------------------------------
Now we have our numbers array which can only hold eight ints. So, let's put
some data into it. The way we get a spot in the array is by indexing it.
Here is how we would get the 4th piece of data from the numbers array.
int fourth = numbers[3];
Q: Why 3?
A: Because array indices always start at zero, if we wanted the first piece of
data, we would say numbers[0]. Always remember that the index is one less
than the element we want. Therefore, the last "cell" in the array would be
cell 7, not 8.
We can also place data into the array in the same fashion:
numbers[2] = 45;
This places the number 45 into the third cell in the array.
Length of an array
------------------
Arrays have a special way of getting their length. It is a variable named
length. To get the length of our numbers array, we would say:
numbers.length //returns the int 8
Iteration and Arrays
--------------------
Iteration is very useful when dealing with arrays. We could easily create an
array that loops through every cell of the array, by having the loop counter
of the loop be the index of the array. This way, we could make an operation
that performs on every single cell of the array.
Create a class named ArrayTest (which should be public).
Code the following methods:
public int sum(int intArray[])
o This method should loop through every cell of the array and return the sum
of all of its elements.
public double[] buildArray(int size)
o This method will create an array of doubles of size "size". Each element in
the array should be 0.1 larger than the first, with the first being 0.0
Example: buildArray(6) would return an array that looks like this:
{0.0, 0.1, 0.2, 0.3, 0.4, 0.5}
public int[] bounds(int intArray[])
o This method will iterate through all elements of intArray and create a new
int array of size 2. This array will have in its zero position, the
smallest value in intArray. This array will have in its one position, the
largest value in intArray.
Example: int numbers[] = {4,6,8,1,4,0,3};
bounds(numbers) would create an array that looks like this:
{0,8}
PHASE IV - Multi-dimensional arrays (instant feedback phase)
==============================================================================
So far, we have worked with one-dimensional arrays. This means that there
is only one sequence being worked with. However, we can link arrays to
achieve the effect of many dimensions.
**************************
*MULTI-DIMENSIONAL ARRAYS*
**************************
If you picture an array as a row, or a list(one dimension): [][][][][]
It can also be pictured as a grid(two dimensions): [][][]
[][][]
[][][]
[][][]
Or as a cube(three dimensions): Not going to try and draw a cube...
This is all in the lecture slides. For this part of the assignment, take a
look at Module 18 of the Lecture slides on the course website. The slides
will come in very handy for future assignments (including this one)
Go back into your ArrayTest class.
Create the following methods:
public static int sum(int twoDArray[][])
o This method will traverse through twoDArray and return the sum of all
elements in the 2D array
public static int[] getRowCounts(int boolean grid[][])
o This method will traverse through grid and return the number of "true's" in
each row of the array. The returned array will be a one-dimensional array
which contains how many occurrences of the boolean value true are in each
row of the array. For the remaining part of this assignment, "row" will
always refer to the first dimension of the array, and "column" will always
refer to the second
Example: boolean grid[][] = {{true, false,false,false}, //Row 0
{false,true, false,true}, //Row 1
{true, true, true, true}}; //Row 2
getRowCounts(grid) would return an array that looks like this:
{1,2,4}
PHASE V - bDEBUG and a debug main
==============================================================================
Now you will learn how to debug your programs.
***********
*CONSTANTS*
***********
Constants are variable in a program whose value never changes. For instance,
the value of PI will never change, so we make it a constant. To make a
constant in Java, use the "final" modifier.
public static final double PI = 3.141592653;
We will use a similar technique to debug our code
debug: To search for and eliminate malfunctioning elements or errors in
source: http://www.dictionary.com
In each one of your classes, create a constant name bDEBUG. It should be
public, static, and of course final. It should be a boolean. Also, give this
boolean a default value of true.
Now, go through some of your methods in IterationTest and find a single line
of code that does something important. Place this line below it:
if(bDEBUG)
System.out.println("Just did something important");
You can use this constant everywhere that you want to see output from a
method. When bDEBUG is set to true, all of this extra information prints out.
If you set the constant to false, it does not. This allows your program to
run in "debug mode".
Add the debug constant to all of your classes and use the debugged prints
often. You will be graded for good use of this. From now on, all methods
which have more functionality than accessors and modifiers will require at
least some debug statements in them.
Debug main
----------
In each one of your classes, make a main method like you did in p0. Your main
method should test all of your methods by making variables/arguments for your
methods, invoking them, and printing out any results. All classes from now
on will require debug mains.
PHASE VI - A world of Cities
==============================================================================
Now that you know how to make Cities, iterate, and make multi-dimensional
arrays, you will put all of it to the test.
Create a class named World.
This class will have a private instance variable named map. This variable
will be an 2D array of Citites. That's right, we can have arrays of Objects.
Each cell in the 2D array will be a City that you created in Phase 1. The
idea of arrays of Objects is also covered in Module 18 of the lecture slides.
Make a constructor for World that take in a 2D array of Cities and assigns the
map variable to it. Now, we're going to give the user the ability to search
this map by "latitude" and "longitude". For the purposes of this project,
this planet will be flat and latitude will be used to access the
x-axis(second dimension) while longitude will traverse the
y-axis(first dimension). Here is a picture of the world:
/ \ [ ][ ][*][ ][ ][ ][ ]
| [ ][ ][*][ ][ ][ ][ ] * = City
longitude [ ][ ][ ][ ][ ][*][ ]
| [*][ ][ ][*][ ][ ][ ]
\ / [ ][*][ ][ ][ ][ ][ ]
<- latitude ->
Note: By default, a 2D array of Objects has all of its values set to null.
----
Create the following method:
public City getCityAt(int lat, int lon)
o This method will return the City which is located at the specified latitude
and longitude. If there is no City there, return null.
public City[] getCititesAtLatitude(int lat)
o Returns an array of all Cities at the specified latitude.
public City[] getCititesAtLongitude(int lon)
o Returns an array of all Cities at the specified longitude
Make sure you use a debug main here as well as plenty of debug staments. You
will want to create the 2D array in the main method as well as all of the
Cities. It is your responsibility to test that each of these methods works.
Hint: use the toString() method of your City class to help.
DELIVERABLES
==============================================================================
Please turn in the following to webwork:
City.java
IterationTest.java
ArrayTest.java
World.java
Make sure that you turn in ALL files by the due time.