Java Arrays
Arrays with 2D images as text.
import java.util.Random;
class TeddyLoop {
//The area between class definition and the 1st method is where we keep data for object in Java
String [][] teddys; //2D Array: AP CSA Unit 8: 2D array of strings
//2D array is like a grid [x][y]
// or like a spreadsheet [row][column]
/**
* Constructor initializes a 2D array of teddys
*/
public TeddyLoop() {
//Storing Data in 2D arrays
teddys = new String[][]{ //2D array above is just a name, "new" makes a container ("object")
//Teddy 0
{
" ___",
" {~._.~}",
" ( Y )",
" ()~*~()",
" (_)-(_)"
},
//Teddy 1
{
" ()=()", //[1][0]
" ('Y')",
" q . p",
" ()_() "
},
//Teddy 2
{
" ()=()", //[2][0]
" (':')",
" d . b",
" ()_() "
},
//Teddy 3
{
" ()-()", //[3][0]
" (^;^)",
" C C ",
" ()_() "
},
//Teddy 4
{
" ()-()", //[4][0]
" ('&')", //[4][1]
" c . c", //[4][2]
" ()_()" //[4][3]
},
};
}
/**
* Loop and print teddys in array
* ... repeat until you reach zero ...
*/
public void printPoem() {
//begin the poem
System.out.println();
System.out.println("5 distraught Teddy Bears in a Store.\nHow many bought? How many more?");
// Random starter array
String[] arr={"Don't worry! ", "Still ", "We have ", "Come quick! ", "Hurry! ", "Just ", "Only "};
// teddys (non-primitive) defined in constructor knows its length
int teddyCount = teddys.length;
for (int i = teddyCount; i >= 1; i--) //loops through 2D array length backwards
{
// Random Word
Random r=new Random();
int randomWord=r.nextInt(arr.length);
//this print statement shows current count of teddys
if(i == 1) {// concatenation (+) of the loop variable and string to form a countdown message
System.out.println("Oh no! " + i + " Teddy Bear in the store!\n");
}
else if(i == 5) {
System.out.println("New shipment! " + i + " Teddy Bears in the store!\n");
}
else {
System.out.println(arr[randomWord] + i + " Teddy Bears in the store!\n");
}
//how many separate parts are there in a teddy teddy?
for (int col = 0; col < teddys[col].length; col++) {
for (int row = 0; row < teddyCount; row++) {
System.out.print(teddys[row][col]);
System.out.print("\t");
}
System.out.println();
}
System.out.println();
//countdown for poem, decrementing teddyCount variable by 1
teddyCount -= 1;
}
//out of all the loops, prints finishing messages
System.out.println("All the teddy bears out the door. :(");
System.out.println("----------------------------------");
System.out.println(" THE END ");
}
/**
* A Java Driver/Test method that is the entry point for execution
*/
public static void main(String[] args) {
new TeddyLoop().printPoem(); //a new teddy list and output in one step
}
}
TeddyLoop.main(null);