SEARCH W7R

Showing posts with label JavaBasics. Show all posts
Showing posts with label JavaBasics. Show all posts

Sunday, September 30, 2012

Java "Hello World" Program

w7r.blogspot.com

Traditionally, "Hello world" is the first program created in any programming language by new users to ensure they are able to compile and run their program in the given language. So I thought it'd be a good idea to post up the code for HelloWorld.java on the site for java beginners.

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

Breaking Down The Code

System.out.println(string)
This statement (or line of Java code) informs the System to print the string (or text referred to by the variable, string) to the console (where output is displayed).
"Hello, World!"
is a string literal. String literals are text that are actually written and displayed exactly as the programmer wrote them. You could replace the text inside the quotation marks with anything you would like to be outputted to the console.

Saturday, June 09, 2012

Java String Methods - Length

w7r.blogspot.com

The "string".length() Method

Length is a method/function used to obtain how many characters are present. These characters include spaces, punctuation, underscores, symbols in unicode, numbers and just about anything else you can think of.

For example, "iRobot" is a string that contains 6 characters, 'i', 'R', 'o', 'b', 'o', and 't'. Each character has its own index (location) in the String, in which calling "iRobot".length() will specify how many characters or spaces there are in the String.

This knowledge would be useless without an application so imagine you, a software developer, needs to ensure your clients names will fit on the screen of your newly built program. Without going through your clients one by one, you could use the length function on each one of their names in your database to find the longest name you must display. Code for this will be in example #1.

Example #1

public static void main(String[] args) {
 String[] clientNames = new String[]{
  "Jacobs", "Trout", "Semor", "Lee","Poppins",
  "Jenson", "Johnson","Peterson", "Kim", "Brown"};

 int longest = 0;

 for(String s: clientNames) {
  if(s.length()>longest) {
   longest=s.length();
  }
 }

 System.out.println("Minimum characters for display: "+longest);
}


In example #1 the length method is used to figure out which string has the most characters. It is important to realize that Strings do not have a character at someString[someString.length()] would throw an exception and terminate your program. Remember that arrays and Strings alike are indexed starting with 0.

The last character of a String can be obtained by someString[someString.length()-1].

More On Java Strings

Thursday, May 10, 2012

The Substring Method of Java

Substring is a method/function used to select smaller strings in the String it was called on.

For example, "CatDog" is a string that contains two smaller strings, "Cat" and "Dog"
To break this "CatDog" string into the two seperate strings, "Cat" and "Dog" one would use the substring method.
Example #1:
//declaration and initialization of string1
String string1 = "CatDog";
 //prints out result of substring(2) 
System.out.println(string1.substring(2));
After running the code above you it is easy to realize we have a problem. Your console should read "tDog" which means we have not split the string1 up as we had planned. The reason is because the parameter we assigned to be 2 should have been 3. Below is the code for what we truly wanted. Goes to show that print statements are a good way to test/debug your programs!
String string1 = "CatDog";    //declaration and initialization of string1
System.out.println(string1.substring(2));    //prints result of substring(2) 
The first and only parameter in example one specified the first character of the string to start the substring from and then because there was no second integer parameter the method returned that first letter and all the characters that followed it in the string.
Example #2:
String quote = "code the gnar";
String word = quote.substring(1); 
System.out.println("original value: "+quote);
System.out.println("final value: "+word);
It is important to realize that there are more than 1 ways of calling for a substring() on a string. In the following example you will see an example using the substring(int,int) syntax. See if you can figure out what the 1st and 2nd integer paremeters are doing!
Example #3:
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String letters = alphabet.substring(5,0); 
System.out.println("original value: "+alphabet);
System.out.println("final value: "+letters);

Click here to see the role of the 1st integer.
Starting index for the string

Click here to see the role of the 2nd integer.
How far after starting index to span

Friday, January 20, 2012

Who Knew Random Took So Much Thought

If I asked you to give me a random number within 1 to 100 from the top of your head what would you pick?
Would your pick be completely random? If you kept asking yourself for random numbers between 1 to 100 chances are you will repeat numbers several times before even reaching your 50th "random" number. If our brain is not able to respond randomly, do you think randomness exists in nature at all? 


Surprisingly, true randomness is arbitrary (made up) just as much as numbers are themselves. Randomness is a way of describing something that is "completely" unpredictable. Sadly, nothing can be completely unpredictable, or perfectly just, because in nature we experience patterns, sometimes clear ones like the stems of plants and other times obscure ones like the orientation of the mushrooms relative to one another after a light rainfall. The patterns that govern our world are infinitely big, so there is no saying that any human will live to see the completion of some patterns that exist as a function of time.

Why would I or you, a tech enthusiast, a student, or a professional care about the randomness in nature? It is because successful programs, algorithms, and other functions that simulate the real world need to be able to be as close as possible to our theoretical values that have been proven time and time again. Probability for one, is extremely important to the fields of computer science, math, and engineering (of course there are many more fields too) because the products of technology solve problems based on theoretical representation of real life variables.

So, the reason I have been indulging in the thought of randomness is mainly because I have been programming my own version on Tetris in Java code and have realized the inaccuracy in the random function of the Math class. Basically, programming languages cannot generate random numbers without following some pattern or algorithm which means that they are slightly predictable and unusual. By unusual I mean that I may have five blue tetrominos (one of seven of the tetris pieces) in a row, "randomly." The chances of that occuring are (1/7)^(5) * 100 %. I did the math for you: 0.0001214265% chance of that occurring. As a stern programming I wanted to fix this ASAP, well lets say ASAP did not come as soon as I wanted. Turns out the "Math.random()" command generates a psuedo-random number which has poor acurracy as far as random goes. Math.random() would be sufficient for many programs, but in tetris if the pieces are being distributed unevenly, then each game will be more or less fair depending on how the beginning value the psuedo-random algorithm uses.

I wanted to have a little experiment or two, so I did. Here is my code for checking how the random values have been. And don't worry, I'll do my best to explain each step in lines of comments (comments follow double forward slashes //). And the class this was used in I called GameStats. GameStats has a


public static void printPieceStats() {
        int total = pieces[0]+pieces[1]+pieces[2]+pieces[3]+pieces[4]+pieces[5]+pieces[6];

        System.out.println("\nL_PIECE (blue): "+pieces[0]+"   |  Percent: "+((pieces[0])/(double)total)*100+"%");
        System.out.println("J_PIECE (orange): "+pieces[1]+"   |  Percent: "+((pieces[1])/(double)total)*100+"%");
        System.out.println("I_PIECE (teal): "+ pieces[2]+"   |  Percent: "+((pieces[2])/(double)total)*100+"%");
        System.out.println("Z_PIECE (red): "+ pieces[3]+"   |  Percent: "+((pieces[3])/(double)total)*100+"%");
        System.out.println("S_PIECE (green): "+pieces[4]+"   |  Percent: "+((pieces[4])/(double)total)*100+"%");
        System.out.println("O_PIECE (yellow): "+ pieces[5]+"   |  Percent: "+((pieces[5])/(double)total)*100+"%");
        System.out.println("T_PIECE (purple): "+pieces[6]+"   |  Percent: "+((pieces[6])/(double)total)*100+"%");

        System.out.println(total);
        //ideally each piece would be dropped 1/7 of the time.
        double ideal = 1.0/7.0*10.0;

        double[] dubs = new double[7];
        int place=0;
        for(int num: pieces) {
            dubs[ place ]= (num/(double)total)*10.0;
            place++;
        }

        //find their percent error.
        //store the percent error
        //use absolute value to stabilize signs.
        //average all of the percent errors together
        double [] percentErrors = new double[7];
        place=0;
        double errorTotal=0;

        for(double d: dubs) {
            double dub = Math.abs((d-ideal)/(ideal)*100);
            percentErrors[place]=dub;
            errorTotal+=dub;
            place++;
        }

        //errorTotal is the sum of % error of each piece which is divided by 7 to yield the average percent error.
        System.out.println(errorTotal/7);
    }

I use the value that is printed out to determine how close my program is to being completely random. I coded this method and you are free to copy and paste the code. The same method could be adapted for all kinds of applications, just follow its steps that are commented in the code.

Java's Math.random Explained!

The command, Math.random() Explained!

Math.random is an important feature of the Java programming language. It generates psuedo-random numbers which in simple terms are approximated random values.

For most applications written in Java, Math.random is upredictable enough to be considered random.

So what does the command do exactly?
Math.random() creates a value from between 0 and 1; a fraction, essentially.

See it for Yourself!
Copy and paste the following code into a main method of any java class. 

/**This will be a double value between 0 and 1. 
* The value discludes 0 and 1,
* so it is non-inclusive or exclusive
*/

//Prints a random number (0 to 1) to the console.
System.out.println(Math.random());

The Realistic Application Of Math.random()
Programmers can get integer (-1,0,2,3,4,5, ect...) values randomly by manipulating the double (decimal/fraction) value returned by Math.random().

int lowNumber = 1;
int highNumber = 6;

//This code is actually an algorithm for getting random integers by means of Math.random()!
int faceOfDice = (int)((Math.random() * 6) + 1);

//Print out the result
System.out.println("Face of die: "+faceOfDie);