Iteration Mini Lab - The Food Cycle
Iteration allows you to go through a list of items relatively quickly. It is easier to store items in a list (known as an array) and then call forth each item later, rather than have to list everything out each and every time.
public class FoodCycle{
String [][] foodcycle;
public FoodCycle(){
foodcycle = new String[][]{
{
" .--. .--. ",
" : (\\ . _......_ . /) : ",
" '. ` ` .' ",
" /' _ _ `\\ ",
" / 0} {0 \\ ",
" | / \\ | ",
" | /' `\\ | ",
" \\ | . .==. . | / ",
" '._ \\.' \\__// './ _.' ",
" / ``'._-''-_.'`` \\ ",
" "
},
{
" . ",
" / V\\ ",
" / ` / ",
" << | ",
" / | ",
" / | ",
" / | ",
" / \\ \\ / ",
" ( ) | | ",
"_________| _//_ | | ",
"<__________\\_____) \\__) "
},
{
" / \\__ ",
" ( @\\___ ",
" / O ",
" / (_____/ ",
"/_____/ U ",
" ",
" ",
" ",
" ",
" ",
" "
},
{
"|\\---/| ",
"| o_o | ",
" \\_^_/ ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
}
};
}
public void print(){
System.out.println(" ");
System.out.println("The Food Cycle");
int animalCount = foodcycle.length;
for (int i = animalCount; i > 0; i--){
System.out.println(i + " animals left ");
for (int row = 0; row < foodcycle[0].length; row++){
for (int animal = 0; animal < i; animal++){
System.out.print(foodcycle[animal][row] + "\t");
}
System.out.println();
}
System.out.println("An Animal has been eaten!");
System.out.println("Run for your lives!");
System.out.println("\n--------------------------------------\n");
animalCount -= 1;
}
System.out.println("No more animals :( \n");
System.out.println("--------------------------------------");
System.out.println(" THE END ");
}
public static void main(String[] args){
new FoodCycle().print();
}
}
FoodCycle.main(null);
Iteration Using Objects
This example could also be in the form of objects. Because the static key word, a class can be created from the animals alone, which creates animal objects and also perform methods. In this sense, the class has universal methods which can be called to do something to the objects it (the class) created.
By using object oriented programming (OOP), the animals are much easier to replicate and they can be given other properties such as names, age, type etc. So, unlike iteration using purely 2D arrays, each fish can have unique properties. Both of them, however, are relatively easy to expand the list that the print function iterates through. However, OOP makes it far easier to manipulate the data of the fishes and the list that is iterated through.