Monday, March 12, 2012

Creating a random zoo

Let's say you wanted to monitor a zoo that you own.

In this zoo you have multiple animals already in there and they randomly are doing things. They are either eating, sleeping, playing, or wandering. Now there is no set order for how they will do these things so we want to have it randomize. We also know that they are never doing the same thing twice in a row.

We also can accept adding new animals. And we can remove animals from our zoo, but only if they are there.

There is no limit to how many animals you can have in your zoo.

You can have multiple of the same animal, but they cannot be listed separately.

Also, you can add more activities.

Now we need to think about how to approach this problem. So lets list what we know and ways to go about programming it.

So we know that we have multiple animals already in our zoo. So we have to make those animals. However, they have activities they are doing. So we can't just use a string. We need to make a class/struct like we did in the previous one.

We also can add new animals to our zoo. So in our class we are going to make a function for making a new animal.

We also need to be able to randomly see what the animal is doing. We can't allow them to do the same thing twice. I'll be demonstrating this in Java this time.

Notice that it doesn't say whether to have it run endlessly or not. We are going to implement the option to run endlessly regardless.

The way we create a list without a limit is by using an ArrayList or a Vector(THIS IS C++).

An Arraylist is essentially a self re sizing array. Same with vector. They are very nice in the fact we do not have a limit to how many things are going to be in our list. Also, they have a lot of nice functions that go with them.

So i made two classes. ZooDriver(Where I run the program.) and Animals(a class for making animals).
ZooDriver.java
import java.util.ArrayList;
import java.util.Scanner;

public class ZooDriver {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);// System.in is how we take input
// in java
ArrayList activities = new ArrayList();// Since we can
// have multiple
// activities
activities.add("Sleeping");
activities.add("Eating");
activities.add("Playing");
activities.add("Wandering");
ArrayList animals = new ArrayList();// More than one
// animal
addAnimals(animals, "Tiger", false);
addAnimals(animals, "Tiger", false);
addAnimals(animals, "Tiger", false);
addAnimals(animals, "Tiger", false);
addAnimals(animals, "Tiger", false);
addAnimals(animals, "T-Rex", false);
addAnimals(animals, "Panda", false);
addAnimals(animals, "Monkey", false);
addAnimals(animals, "Monkey", false);

System.out.println("Welcome to the Internet Zoo!");
String check = "";
while (check != "5") {
System.out.println("What would you like to do?");
System.out
.println("1. See all the animals and what they are doing?");
System.out.println("2. See a specific animal and its activity?");
System.out.println("3. Add a new animal to the Zoo?");
System.out.println("4. Add a new activity?");
System.out.println("5. Quit");
check = scan.next();

// So we have 5 choices which means we need 5 if statements. But
// since our while takes care of our quit. We just need 4.
while (!(check.equals("1") || check.equals("2")
|| check.equals("3") || check.equals("4") || check
.equals("5"))) {
System.out.println("That is not valid input");
System.out.println(check);
check = scan.next();
}
if (check.equals("1")) {
for (int m = 0; m < animals.size(); m++) {
System.out.println(animals.get(m).toString(activities));
}
System.out.println("\n"); // wanted more spacing
} else if (check.equals("2")) {
System.out
.println("What animal do you want to see?(Not case sensitive)");
String specific = scan.next();
specific = specific.toLowerCase();
for (int m = 0; m < animals.size(); m++) {
if (specific.equals(animals.get(m).getName().toLowerCase())) {
System.out.println(animals.get(m).toString(activities));
}
}

} else if (check.equals("3")) {
System.out
.println("what animal do you want to add?(Not case sensitive)");
String add = scan.next();
addAnimals(animals, add, true);
} else if (check.equals("4")) {
System.out
.println("What activity do you want to add?(Case sensitive!)");
String add = scan.next();
if (activities.contains(add)) {
System.out.println("This is already in the list!");
} else {
activities.add(add);
System.out.println("Added!");
}

}
}

}

public static void addAnimals(ArrayList list, String k,
boolean print) {
for (int m = 0; m < list.size(); m++) {
if (k.toLowerCase().equals(list.get(m).getName().toLowerCase())) {
list.get(m).amount++;
if (print)
System.out
.println("Already in the list, but added to its friends");
return;
}

}
Animal temp = new Animal(k);
temp.amount++;
list.add(temp);
if (print)
System.out.println("Added!");

}
}

Animal.java
import java.util.ArrayList;

public class Animal {
String name;
int amount;
int previous;
String current;

public Animal(String name) {
this.name = name;
amount = 0;
previous = 0;
current = "Sleeping";
}

public String getName() {
return name;
}

public int getAmount() {
return amount;
}

public String activity(ArrayList list) {
String temp = current;
int rand = (int) (Math.random() * list.size());
current = list.get(rand);
while(temp == current){
rand = (int) (Math.random() * list.size());
current = list.get(rand);
}
return current;
}
public String toString(ArrayList list){

String temp = "There is ";
if(amount > 1){
temp = "There are ";
}
temp += getAmount() + " " + getName();
if(amount > 1){
temp += "s and they are " + activity(list);
}
else{
temp += " and it is " + activity(list);
}
return temp;
}
}

Hope you guys enjoyed reading this and have a nice day!

Also, I couldn't find a function in java to clear the console so I ended up making a pretty lame boolean to prevent myself from printing out before the initial questions.

Thank you!

Everett

Friday, March 9, 2012

Really Basic programs + learning arrays!

Anyone who has ever taken a course in programming knows all about hello world. It's a program that essentially is just a statement that prints out the words "Hello World! My name is [insert name here]!" I'm going to demonstrate this one. It's very easy.


C++ version first

#include (Note: This allows us to print out using cout and take input using cin.)

using namespace std;

void main(){
cout << "Hello World! My name is Everett!"<< endl;
}

javaversion

public static void main(String[] args){
System.out.println("Hello World! My name is Everett!");
}

Both of these programs do the same thing. They just simply print out the words inside the quotations.

Time to introduce the String type. The words between the quotations are considered a temporary string. A string is a collection of characters. It can be multiple lines, it can be one line, it can be empty, and it can be one letter. Pretty much anything can be stored in a string.

Another type is int. Int is short for Integer. As we all learned in arithmetic an integer is a whole number. It's the same in programming.

The next type is double. A double is what we would categorize as any possible number. It doesn't have to be whole, it can have .5 in it. It is any value. This has its advantages and its disadvantages as well.

And the next main type is Bool. A bool, or Boolean, is a statement either true or false. No ifs or buts about it. It is either TRUE or it is FALSE. In C++ it is either a 0( indicating false) or anything else. It can be a word. It can be a negative value. it can be anything.

These four data types will take care of just about every problem you can come by.

Now if you needed to make a new data type. Let's say you are the boss of somewhere and you need a list of people. And each of those people have a few specific things to each of them. Those things being; the amount of hours they work, their pay rate per hour, and their name. Also, for simplicities sake lets say its up to 100 workers. We are going to use arrays.

An array is essentially a list of things. When you declare an array you have to declare how big it is. So lets say we want to go shopping and we can shop for up to ten things. Our array would be
string shop[10];

Think about it like a piece of paper with 10 lines on it. You can't add any more lines to it. And you can't remove any lines from it.

So in order to make a data type in C++ you would need to make a struct.

The format for making a struct is.

struct NAME{
variables
variables
variables
}NAMES;
In java you make a new class with the name of the data type. So lets say you make a class called people.

public NAME{
variables
variables
}

Now lets fill it in for how we want it for this boss.

Quick thing about the cin / cout stuff in c++. When you use a cin. You assume that you are taking in input from the command line. The user will input something in. They will almost ALWAYS mess it up. If you put a string in where you ask for an integer.... scary things happen. Thank goodness for the checks we have. We can use cin.fail() to see if they put that in. Also we can check the input to make sure it is valid.

Another thing about cin. Let's say you are asking for a string. A one word string. They in put the word "Cheese". You store that. But what they really typed is "Cheese\n" The cin doesn't grab the \n. It just leaves it there for you to deal with later. In order to get rid of it you want to use cin.ignore(1000, '\n'). I choose 1000 because its a large number. You can put any large number in there. And I am using '\n' because that is what I want to ignore.

Now in order to get multiword input on a single line you use
getline(WHERE FROM, Store where?);
So an example would be
string wholename;
getline(cin , wholename);

The where from dictates that we are getting it from the C input. Which is the command line in this situation.



C++ FILE STARTS HERE.

#include
#include

using namespace std;

struct people{
string name;
int hours;
double payrate;
}list[100] , employee;

void main(){
int size = 0;
int n = 0;
cout << "Welcome to the employee listings!" << endl;
while( n != 4)
{
cout << "Please select an option" <> n;
while(cin.fail() || n > 4 || n <= 0){
cout << "Please try again" << endl;
cin >>n;
}
if( n == 1) {
cout << "What is the new employees name?" << endl;
string temp;
cin >> temp;
while(cin.fail()){
cout << "Please try again" << endl;
cin >>temp;
}
employee.name = temp;
cout << "How many hours do they work?" << endl;
int n;
cin >> n;
while(cin.fail()){
cout << "Please try again" << endl;
cin >>n;
}
employee.hours = n;
double m;
cout << "How much do you pay them?" << endl;
cin >> m;
while(cin.fail()){
cout << "Please try again" << endl;
cin >>m;
}
employee.payrate = m;
list[size] = employee;
size++;
}
if(n == 2)
{
cout << "What's their name?" << endl;
string temp;
cin.ignore(1000, '\n');// <--- this clears the buffer from the earlier cin. When cin grabs a value it leaves a value in the buffer. The buffer is what your program looks at when you use a cin.
getline(cin, temp); //<----- This function grabs a whole line of words. the regular cin just grabs one object until it finds whitespace.

for(int m = 0; m < size; m++)
{
if(list[m].name == temp)
{
for(int x = m; x < size - 1; x++)
{
list[x] = list[x + 1];
}
size = size - 1;//(can be shortened to size--;)
}

}
}

if( n == 3 )
{
for(int m = 0; m < size; m++)
{
cout << list[m].name << " is paid " << list[m].payrate << " and he / she works " << list[m].hours << " a week. " << endl;
}
}

}

}

Now that's the end of the C++ code. It may seem a bit daunting. But its only using a few things that I've talked about here. Remember that this is low level programming. I have not shown how to deal with text files and everything else yet.

Also, this code is not efficient. It also doesn't use anything very dynamic yet. We will talk about vectors, arraylists, maps, hashmaps, sets, treesets, trees, and much more in the future. This is just to show how I plan to discuss and to show you these things.

AND I CAN'T FIGURE OUT HOW TO DO THE FORMATTING ON THIS BLOG D:

Thank you for reading!

While Loops

While Loops are extremely powerful. They allow you to continually do something WHILE something is true. The format for doing a while loop is as follows:

while(SOMETHINGisTrue){


}

or
while(somethingIsTrue)
{

}

Both are perfectly acceptable formats. Remember the if statement I discussed in my previous post? This is almost exactly the same. Let's say you have a value of x that is a negative number you want to be greater than zero. So with the if statement it would look something like this.

int x = -5;
if(x < 0){
x++;
}

System.out.println(x);(JAVA)

or

cout << x << endl;(C++)

Note. x++ is shorthand for x = x + 1.

Now an issue with this code is that it will only go one time. It would yield a result of -4. This doesn't quite complete our goal. So we want to use a while loop. The result of using a while loop would look like this.

int x = -5;
while(x < 0){
x++;
}
System.out.println(x);
or
cout << x << endl;

Now the way that this is computed is like this.

First thing that happens is that x is assigned the value of x. Following this we have a while loop statement. Remember that this works similar to how an if statement works.

So the second thing that happens is we check the value of x. We find that it is -5. The value is then checked to see if it is less than 0. We find that it is so we continue through our loop.

The x is then incremented. At the end bracket our program then does a check in the while loop to see if it is still true.

while(x < 0){
x++
}It checks right here. Right before it tries to exit the loop.

Then it finds that the statement is still true. So it repeats our third step of incrementing. It continues to do so until the value in the while statement is proven to be false.

Thank you for reading! As soon as I'm done explaining the lower level things in programming I'll start discussing the projects that I encounter and strategies I try to use to solve my problems.

Thursday, March 8, 2012

Goals of this Blog

So for those of you who are reading this, I hope its not that bad! I am trying to solidify concepts in programming for me. Majority of the things I will discuss are very basic. I am primarily programming in C++ and Java. Java being the emphasis at this point in time. So for my first post I'm going to discuss if statements.

The most important thing about if statements is that it takes in a boolean value in it. The general format of an if statement is as follows

if(somethingIsTrue()){
then do the following.
}
else{

}

Now an important part of a boolean is that in C++ a true value is anything that is not zero. So if you do

if(1){
then do something
}
else{
quit
}

Then it would proceed to do something. This is very useful for when you return a null value(ZERO!) or an actual value(Say 10000, or something like the word cow). This allows us to use it a little bit more dynamically.

Another thing is the formatting. There are a few different formats for doing an if statement. The generally accepted ways you should format are as follows;

if(somethingIsTrue)
{
then do something
}


OR

if(somethingIsTrue){
then do something
}
To sum it up.


An if statement allows us to control whether we do something or not. Which is a lot of trouble.

if(somethingIsTrue()){
then do whats in the brackets.
}

Thank you for reading! Please leave comments in the bottom. I intend to use this blog to help me learn!