Saturday, December 8, 2012

12/8/12 Object Arrays

You know what an Object is, and you also know what an Array is, but did you know that you can have an Array of Objects? This means that you could have an array that is a address book; holding objects that represent people in the book. These people will have primitive variables for their address and their phone number. In this post, I will teach you how to use objects in arrays. For this post, I will use the example of people in a phone book.

To create the phone book, you would type:

person[] phoneBook;

This will create an array of people, named phoneBook. Because I did not give phoneBook a size, it is currently pointing to null (nothing). We can fix this problem by saying:

phoneBook = new person[numberOfPeople];

This will give phoneBook the ability to hold numberOfPeople people. What would happen if we then tried to print the elements of phoneBook? Well, we would just print null a bunch of times in a row. To fix this problem, we would need to create a for loop to go through each element of phoneBook and fill them all with the default person. To fill an element of the array with a new person, you would type:

phoneBook[index]= new person();

Now if I wanted to have a value for the person's name, address, and phone number, I would type:

phoneBook[index]= new person(name, address, phoneNumber);

To call a method from a person in phoneBook, I would put phoneBook[index]. and then the method that I want to use. This would allow for me to access the names, addresses, and phoneNumbers of each person in phoneBook.

This is more or less all that you need to know about arrays of objects. Hopefully you have learned a thing or two about java, and I will see you again next week!

Saturday, December 1, 2012

12/1/12 How objects really work

A long time ago, I discussed Objects and Instance variables. As you may or may not remember, an Object is not like a primitive data type, but more like a collection of primitive variables that can also be manipulated by the Object. To create an object, you would type:

(Object name) (name) = new (Object name)((parameters));

This code will simply create a (Object name) with the name (name), and starting values (parameters) for the variables in the object that you are creating. Now, what would happen if I tried the following code without a toString method in (Object name)?

System.out.println((name));

Well, you should get something weird like Obj@1cd2e6f. You may then be wondering "what dose this mean?", well it is telling you where in your computers memory you are storing (name). This means that (name) is not actually a (Object name), but a pointer saying where in the memory to look for (name). This may not seem like it makes that much of a difference, but it dose. Let's take the following code:

Object a = new Object(1,"hi");
Object b = new Object(1,"hi");
if(a==b){
 return true;
}
else{
 return false;
}

It seems that this code should return true because the two objects are the exact same, but it dose not. It fails to do so because this code is simply checking if a has the same memory address as b doses. If you want to see if two objects are equal, you will need to create a equals method for that object. This has one other implication, what do you think will be the output of this code:

Person a = new Person("Bob");
Person b = new Person("Joe");
b=a
a.setName("Smith");
System.out.println(b.getName());

It should be Bob, but remember that the name a or b is simply pointing to the object that it is representing, meaning that when you are saying that b = a you mean that b is now pointing to the same place in memory as a is. This means that both person a and b are the same person, and both have the name Smith, so the output would be Smith.

Hopefully you have learned a thing or two about Objects and how they work in Java

Sunday, November 18, 2012

11/18/12 Matrices

Two posts ago, I talked about arrays. Did you know that you can make an array of arrays? These arrays will work like a matrix in java. Today I will teach you how to use arrays of arrays or matrices in java.

Think about an array as a line, it exists in exactly one dimension. Now for each point on that line, place a line that is perpendicular to the starting line. Now Image this with arrays instead of lines. This basically gives you a plane filled with data on points, or a matrix. This means that we can view a matrix as simply an array of arrays.

Now that you know this, you may be wondering how you initialize an array. To do this you would type:

(type) [][] (name);

Where type is the data type that you want to use and name is what you want to name the matrix. This will successfully create the matrix, but the matrix will be pointing to null (not there). To get the matrix to point to something, you would type:

(type) [][] (name) = new (type) [(# of rows)] [(# of columns)];

This will create a matrix filled with the number of rows and columns that you want to use. Now that you have the matrix, you probably want to fill it with some data. To add data to a point in a matrix, you would type:

(data you want to add) = (name) [(row)] [(column)]; 

Hopefully you know know something new about matrices (aka arrayception).

Monday, November 12, 2012

11/12/12 Quiz bowl

This has been a very busy week for me, and we did not learn a new topic this week because we had a test. Today I will not teach you something new, but I will talk about the computer science questions that I did or did not get at a quiz bowl tournament this weekend. You can find the stats of the tournament here, and my stats here and here.

Computer science dose not come up very often in quiz bowl, but in a tournament there are normally about 4 questions. The first was a bonus question about data structures. The answers were array, stack, and red black tree. I got array correct, but confused heaps and stacks. For the last part I answered binary tree, and I was prompted but I did not know what a red and black tree was, so I also missed that part. This was probably one of my weakest computer science questions that day. 

Next was a java question. I would have gotten this question if our opponent was anyone but St. Johns A, the players of which just memorize certain key words to answers, which allows them to get questions very early with out knowing very much. Because of this they got the question on the second word, while I would probably have got it about a sentence later.

The third question was a search algorithm question. I was able to get this one when they were talking about big O notation, which can tell you how much time it takes for a search algorithm to run. I knew that the answer was eater going to be search or sort from the start of the question, but I was not sure which until the big O clue.

I am sorry that I did not talk teach you anything new about java, but last week we just studied and took a test on logic, loops, and arrays. Also, I am sorry if this post did not make much sense to you, but I had to miss school on Friday for the tournament and I need to do all my homework today. Just to give you some context, here is an example quiz bowl question:

The next version of this language has the designation 0x (zero x). One important part of this language is templates and it supports references. One can manage memory in it by using the delete and new operators. In it, one can print to the standard output using cout. Unlike its ancestor, this language supports classes. For 10 points, name this programming language whose name reflects that it is a step up from its predecessor, C.

Answer: c++

Friday, November 2, 2012

11/2/12 Arrays

Let's say that you want to create a program that will hold as many Fibonacci numbers as you input. This seems possible with what we know, we could just use a for loop that counts up to the imputed number, defining a variable for each value. This may seem like it would work however, how you need create a variable for EACH number they enter, which could be infinity large. This means that you must define infinity many variables to do this. This may seem impossible, however it is easy if you use an array.

An array is what is called a data structure, meaning that it holds a bunch of variables. A string for example is just a collection of chars, meaning that a string is an array. So, getting back to the Fibonacci problem, you could create an array that contains the entered number of Fibonacci numbers. Here is my code for solving this problem:

import java.util.Scanner;
public class test2{
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        System.out.println("how many numbers?");
        int HowMany = scan.nextInt();
        int [] test = new int [HowMany];
        test[0]=1;
        test[1]=1;
        for(int runs = 2; runs<HowMany; runs++){
                test[runs]=((test[runs-1])+(test[runs-2]));
        }
            for(int runs = 0; runs<HowMany; runs++){
                System.out.print(test[runs]+" ");
            }
        }
    }


In this code, test is an array, and when I wanted to use or edit a value of a number in the array, I put test[x], where x is the index that you want to reference. If any of this is confusing to you, please tell me, and I will do my best to clarify for you. Hopefully you learned a thing or two about arrays and java.

ps, for Halloween, I dressed up as windows vista =)  

Sunday, October 28, 2012

10/28/12 The scanner library

Today I will teach you all about the scanner library. I used the scanner library in my last post, but I just realized that you may not yet know what it does! A scanner is a pre-programmed object in java that allows you to input data from the user. To be able to use a scanner in your program, you must first type the following code into your program before the start of the class:

import java.util.Scanner;

That will tell java that you want to use the scanner library for your code. Now that you have imported the scanner, you will need to create a scanner in your code:

Scanner scan = new Scanner(System.in);

This will create a new scanner named scan. Now that you have a new scanner, you can input data from the user. If you want a integer, you type:

int i = scan.nextInt();

For a double, you type:

double d = scan.nextDouble();

For a single word, you type:

String s = scan.next();

For multiple words, you type:

String m = scan.nextLine();

There is one problem with the next line method that you need to be aware of for your code to work properly; if you have a scanner method followed by a nextLine method, the nextLine method will not run. To solve this problem, you add another nextLine that is not attached to anything. This line will then be skipped instead of the line that you needed to run. The second error that you need to look out for is if the user enters a invalid data type. You can solve this problem by using the has method. The has method will check to see if the input is the correct data type and return a boolean value. Here are the has methods:

hasNext()
hasNextLine()
hasNextDouble()
hasNextInt()

Each of these methods check for the the corresponding return type. This is pretty much the basics for the scanner method, so hopefully you have learned a thing or two about the scanner method in java, and please post any questions that you have about anything that I have said in this or any other post in the comments below.

Sunday, October 21, 2012

10/21/12 For loops

Today I will teach you about For loops. A for loop has three components, an initialization, a condition, and an increment. The initialization will define a new variable with a scope of the for loop, and the condition statement will contain a boolean value that will cause the for loop to run again if the condition is true at the end of the loop. The increment will modify the value of the initialization variable each time the loop runs. Here is how you would code a for statement in java:

for(type var; condition; increment){

}

Now that you know how make for statements, I will show you an example for how to use them:

int total = 0; 
Scanner scan = new Scanner(System.in);
System.out.println("how many numbers?");
int times = scan.nextInt();
for(int timesDone = 0; timesDone<=times; timesDone++){
  System.out.println("number?");
  int number = scan.nextInt();
  total+=number;
}

System.out.print("the total is " + total);

This code will first ask you how many numbers you want to add up and then it will prompt you for those numbers one at a time. It then prints the total of those numbers added together.

Hopefully you have learned a thing or two about for loops in java, and if you have any questions, feel free to post them in the comments. I would also like to know if anyone has any suggestions for how to make these posts better.

Saturday, October 13, 2012

10/13/12 If and else

Today I will teach you about If and else statements and how to code them in Java. Last week, I tough you how to use booleans and evaluate if a statement is true or false. An if statement runs if and only if the boolean that is entered as a parameter is true. If the parameter is false and you have an else statement right after the if statement, then the else statement will run instead of the if one. This is an example of an if statement in Java:

boolean b = true;

if (b){
 System.out.println("true");
}

else{
 System.out.println("false");
}

This code would print the word true. If b was false instead of true, the code would print false instead. Instead of just entering a boolean by the if statement, you actually can enter any statement that can be evaluated as eater true or false like 2<4 or 1==2. This is a very simple way to use if statement, but you can do more than just this! If you want to, you can have else if statements that only run if the code before it was false and did not run. This is how it would work:

int test = 3;

if (test == 1){
 System.out.println("one");
}
else if (test == 2){
 System.out.println("two");
}
else if (test == 3){
 System.out.println("three");
}
else if (test == 4){
 System.out.println("four");
}
else if (test<=0){
 System.out.println("less than or equal to 0");
}
else{
 System.out.println("greater than or equal to 5");
}

This code would print the word four, but if test was one the code would print one, two it would print two, three would print three, if test was less than or equal to zero, it would print less than or equal to zero. Now if test was anything else, it would print greater than or equal to 5. Because there is no if after the last else, if none of the else if statements work, then the else statement will run.

Hopefully, 

if(you read this post){
 System.out.println("you have learned a thing or two about if and else statements");
}
else{
System.out.println("you should read this post so that you can learn more about if and else statements");

=)

Sunday, October 7, 2012

10/7/12 Booleans and basic logic

Today I will teach you about logic with booleans. A boolean is a primitive data type that can  only hold a value of 0 or 1. In computer science, You use booleans to represent if a certain statement is true (1) or false (0). An example of a true statement is 2==2 and an example of a false one is 2==3. In java, you can also do complex statements that my include and (&&) or or (||).

Just in case you do not fully understand what I just said, let me give you some examples of what I meant:

1 == 2; is false
2 ==2; is true

Using and and or makes this a little bit more complicated. For && the statement is true iff both sides of the equation are true while for || the statement is true if ether side of the equation is true. I will give you some examples:

true && true; is true
true && false; is false
false && false; is false
true || true; is true
true || false; is true
false || false; is false

We can use both && and || in the same expression. If we do this, we need to know that you evaluate && before ||, but if something is in parentheses, you do that first.  Here are some examples:

true && true || false; is true
false && true || false && false; is false
(true || false) && (false || false); is false
false || true && (false || true); is true

These can get infinity complex, but here are some helpful shortcuts to telling if something will be true or false:
1) true || (stuff) is always true
2) false && (stuff) is always false

Hopefully you learned a thing or two about booleans, and please comment if you have any further questions.

PS- This Saturday, I went to a Quiz Bowl tournament and our team won! Go LASA!

Saturday, September 29, 2012

9/29/12 Instance variables in objects

In my last post, I explained what an object is in java. Objects use instance variables, which are variables that can only be accessed and changed using the object itself. If you want to find out what value an object has for a certain variable, you need to program the object to give you the variable. If you want to edit a variable, you need to program the object to change the value of that variable from an outside source. How do you do this, you may ask? Well, in this post I will teach you how to build a object such that you can let another class both  find the value of and edit its variables.

To do this, I will write out the code, and write // followed by an explanation of what it does.

public class object{

 private int a;
 private int b;
 //This creates 2 instance variables named a and b

 public object(){
  a = 0;
  b = 0;
 }
 //This defines the default value of a and b for a new instance    
 //of the class object

 public object(int newA,int newB){
  a = newA;
  b = newB;
 }
 //This defines the values of a and b for a new instance of the 
 //class object

 public void setA(int newA){
  a = newA;
 }
 //This will allow for you to change the value of a from outside 
 //the class object

 public void setB(int newB){
    b = newB;
 }
//This will allow for you to change the value of b from outside 
//the class object

 public int getA(){
  return a;
 }
 //This will return the value of a where it is needed outside of 
 //the class object


 public int getB(){
  return b;
 }
 //This will return the value of a where it is needed outside of 
 //the class object

 public String toString(){
  return a + " " + b;
 }
 //This will return a summery of all the variables in the class 
 //object to where it is called in another class

}


Hopefully you have learned a thing or two about objects, classes, and instance variables. If you have any questions, just post them on the comment section, and I will get back to you ASAP.

Sunday, September 23, 2012

9/23/12 Object basics

Java is considered a object oriented programming language, so it it all about objects. Objects are substances that have "rules" that govern them, and you can create as many of the same object as you want in your program. All of these instances of the object can be manipulated differently, but they all have the same code.  In this post, I plan to teach you about objects.

Unlike integers and other primitive data types, objects do not have a limited space that they occupy on the computer. When I was teaching you about integers, I mentioned a bunch of calculations that you can do to those integers. Objects are not like a variable, but more like a physical object. This physical object can have multiple properties that describes how it looks and acts. These properties are like variables that describe the object, so an object could have a variable that describes how tall it is, or how fast it is traveling. Physical objects can also do things like move around and eat stuff. Guess what, you can also make objects in your program do things! To make your object do things, you will need to create and code a method for what you want your object to do.

If you are still not fully understanding how an object works in java, I will give you an example. Lets say that I wanted to make an object that is a sole, I would want to make variables for its height, weight, length, position, speed, how hungry it is, and much more. Some methods that the sole would have would include eating, swimming, sleeping, and hiding.

Hopefully, you now know a little bit more about java, objects, and soles. Thanks for reading!

Sunday, September 16, 2012

9/16/12 Calling a method

When programming in java, have you ever asked yourself the question "do I relay need to type this code over and over again?". If so, welcome to the world of methods. A method is a way to easily recall a piece of code in your program whenever you need it, so if I wanted to have the computer do a large calculation multiple times with different inputs, I would use a method. In this post, I will enplane how to create methods when programming in java.

So, you may be wondering "how do I create a method?", well you will type the following code:

public static [type] [name] ( [data type] [variable name], [data type] [variable name], ...){


}
You may be wondering "what dose this mean?". We will take this one step at a time, starting with public. When you say public, you are saying that this method is available for your program to use. Java is a object oriented language, meaning that all methods and classes are actually objects unless their name contains static.  When you say static in a method, you are saying that this method is not an object in the program.

Normally when you use methods, you are asking for the computer to spit out a piece of data for you. In my last post, I briefly discussed the ways you can store data. In place of the phrase [type], you would insert the data type that you want the computer to spit out. If you do not want to computer to return any data, you would just type void instead of a data type. Where the code says [name], you simply type what you want to call the method.

In parentheses, you would enter the inputs that the code needs to operate. You do this by first typing the type of the variable, and then what you want to call it. Your method can contain as many variables as you would like it to have. You would type the code that you want the computer to run when calling this method between the curly brackets.


Friday, September 7, 2012

9/7/12 Integers

In java, there are multiple ways you can store data on the computer. These are called data types.This week, we have learned about 4 different data types. These data types are integers, doubles, chars, and strings. All of these data types are used to store different kinds of data, like you can store numbers in doubles, but you can not store words in them. Today, I will explain how to create and edit integers in java.

An integer can hold an integer, or a number that has no fractional part. In java, to create an integer you type
"int A;" where A can be whatever you want to call the integer. This will make a new integer, and to give integer A a value, you would type "A = ?;" where ? represents what you want A to equal. As an example, lets say I wanted to create a new integer, call it N, and make N be equal to 5. I would type:
int N;
N = 5;
It is that easy to define an integer. If you want to, you could also type "int N = 5;", and it would create an integer N where N is equal to 5. Now that you know all about how to create an integer, you may be wondering "why is it useful to create an integer?". It is useful to create an integer because you can change what number the integer holds within your code.

Now that you know how to create an integer, you can add, subtract, multiply, or divide to change the value of that integer. I will show you how to change the value of the integer N that I said was 5 earlier in this post.
N = N + 5; (will increase the value of N by 5)
N = N * 5; (will multiply N by 5)
N = N - 5; (will  decrease  the value of N by 5)
N = N / 5; (will divide N by 5)
There is one error that could arise from editing the value of an integer. If you have N, and you divide it by 2, the answer is two and a half. Two and a half is not an integer, so your code will not work if you try to make an integer become a number that is not one. There is a way to fix this problem. If instead of typing "N = N/2;", you type "N = (int) N/2;", N will be truncated down to 2, which is an integer. This works because by typing "(int)", you are telling the computer to give you the answer as an integer. This is all I have to tell you about integers and java, so hopefully you now know how to create and edit integers in java.

*Note: you may have noticed that at the end of each line of code, I put a semicolon. In java, you do this to signify the end of a command.