Wednesday, March 27, 2013

Java;Notes - 14.) Formatting Output

In Java the best way to format an outcome in terms of numbers is to use the "printf" function So it would look something like this:

  1. System.out.printf("Hello %s, next year you will be %d", name, age);
This is the conversion chart for printf:

Here is the Flag chart for printf: 
Note: You can use multiple flags with printf so long as all negatives are enclosed in parenthesis.

Telling date and time:
Since we are experimenting with printf we can also use it to print out the date and time like so:
  1. System.out.printf("%tc", newDate());
Here is a helpful chart for Date Conversions under printf:



One last graph for printf format specifiers syntax layout:



Java;Notes - 13.) Input and Output

Made simple, Input is the act of gathering data from users. As well output is displaying that data. To do this with a terminal is really really simple:

Getting Input(Johny5) and Giving Output:
In order to get input we use a thing called a Scanner which basically takes input from the system and stores it into a scanner variable Here is how to use it:

  1. import Scanner
  2. Scanner input = new Scanner(System.in)
  3. System.out.print(What would you like to output: ") // This causes the cursor to show on this line
  4. String inStr = input.nextLine();
  5. System.out.println(inStr);
Here is the above example in use:

Java;Notes - 12.) Fun with Strings

As you have seen in some of my programs the use of Strings is nothing new. It really helps to be able to use them to make things make more sense. As was a great example two posts ago about rounding numbers either up or down. Had I not added the strings explaining what each output was and had I not shown the code the numbers would have just been numbers. Big whoop anyone can print out numbers its as simple as:

  1. int x = 4;
  2. System.out.println(x);
Or if your really lazy:
  1. System.out.println("3.14159");
Not the last one was a string that was created in the moment. The kinds of strings we are going to be reviewing now are likely a mix of the above and the kinds of strings that hold their own variables and meanings.

To make a static string all you need to do is either of the following:
  • String e = ""; // this will create an empty string which can be useful if you want to input something.
  • String greeting = "Hello!";
Call out the function (String)<Variable> = {Meaning}
Creating strings is not a hard concept to grasp... however what comes next might take a little brain work.

Substrings:
A substring is basically using one already made string to make another one using the characters provided in the main string. Like so:
  • String greeting = "Hello!";
  • String s = greeting.substring(0, 3) 
This will output all of the characters used from point 0(h) through point 3(l) so when you:
  • System.out.println(s);
You will get an output of "Hel"

String Concatenation: 
String concatenation is another simple one. Think of it as "Adding Strings" so the syntax looks like:
  • variable = string1 + string2;
A proper looking code example would be:
  1. int age = 13;
  2. String rank = "PG";
  3. String rating = rank + age;
This should print out "PG13"

The Typical use of the above made string is one I have used before in my calculator:
  • System.out.println("The answer is: " + answer);
Strings are Immutable:
In basic principle java provides no ways to change a given character in a string. However to do this is rather simple. Take our greeting string from before if you wanted to change the "Hel" into "Help" you would simply concatenate a "p" onto the end of it so it would look something like:
  1. greeting = greeting.substring(0, 3) + "p";
In java you can not change a given string once it is made. However using the previous method you can reference a variable and generate a new string from it. It is for this reason that it is called Immutable. However as inefficient as this might seem the new string made has one great advantage. It is shared. Meaning the value of "greeting" goes two ways now.

Testing Strings for Equality:
You can test strings for equality just like you can test numbers. Use the equals method like so:
  • s.equals(t);
This will return true if the strings "s" and "t" are equal and false if they are not.
Note: "s" and "t" can be string variables or string constants. for example:
  • "Hello".equals(greeting);
To test if two strings are the same except for the upper / lowercase first letter you can do the following:
  • "Hello".equalsIgnoreCase("hello");
Empty and Null Strings:
The empty string "" is a string lenght of "0", You can test this by calling either of these two methods:
  • if (str.lenght() == 0)
  • if (str.equals(""))
An empty string holds a value of 0 however if if has no value associated with it it can hold a "null" value to test null you simply:

  • if (str == null)
Sometimes its good to see if a string is neither null or empty to do so you simply do the following:
  • if (str != null && str.lenght() != 0)
Note: you need to test if a string is null before doing the above or else you will get an error for your output.

Code Points and Code Units:

A code unit is defined simply as the number of letters in a unicode UTF-16 strings of numbers and letters to find out how many code points a string has you do the following:
  1. Make a string: String hello = "This is a string, how are you?";
  2. Make an int with the value assigned to it: int numLetters = hello.lenght();
  3. print it out: System.out.println(numLetters); //In this case it will print out 30
To get the true output of the length you must do this:
  • int cpCount = greeting.codePointCount(0, greeting.lenght());
To see what an individual character in a string is do the following:
  • s.charAt(n); // where as n = the position in the string you want to see.
In the case of s.length() you start at -1 So in practicality it would look like:
  1. char first = greeting.charAt(0); //Displays character #1: H
  2. char last = greeting.charAt(4); // Displays character #4: o
  3. System.out.println(first , last);
To get an indexed code point do the following:
  1. int index = greeting.offsetByCodePoints(0, i);
  2. int cp = greeting.codePointAt(index);
  3. System.out.println(index);
 So why is it important to know Code Points? Say you have a character that you dont know the meaning of if you want to know what it is you can use CodePoints to learn what it is.

Viewing Forward:
  1. String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
  2. int i = 0;
  3. int cp = sentence.codePointAt(i);
  4. System.out.println("\n" + sentence);
  5. if (Character.isSupplementaryCodePoint(cp)) i += 2;
  6. else i++;
  7. System.out.println(i);
Viewing reverse:

  1. String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
  2. int i = 0;
  3. int cp = sentence.codePointAt(i);
  4. System.out.println("\n" + sentence);
  5. i--;
  6. if (Character.isSurrogate(sentence.chatAt(i))) i-- ;
  7. else i--;
  8. System.out.println(i);
Here is an image of the output for all of this code:

All of the code in this section can be found: Here!




ADDENDUM: String Builder!
I failed to mention String Builder. String builder is a good tool to use if you need to get parts of a file to be placed in a program and it is really simple to use. Here is the basic outline:

  1. Stringbuilder builder = new Stringbuilder();
  2. builder.append(ch); //Appends a single character
  3. builder.append(str); // Appends a string
  4. String completedString = builder.toString(); // Finallizes and puts it in a nice neat string to print out later!




Tuesday, March 26, 2013

Java;Notes - 11.) Java Enumeration

In java there are many ways to set up a variable to mean something. However setting up some variables can be tedious and give way to issues later on down the line. This is where Enumeration seems to come into play.
Enumeration can be defined as a way to make a custom static variable but in most cases it is a string of variables that will have certain meanings.

Say for instance you are looking to organize your clothing by Size. Instead of it being a set of characters or numbers why not make it an enumeration like so:

enum Size (SMALL,  MEDIUM, LARGE, X-LARGE);
Then you will be able to declare variables of this type such as:
Size s = Size.MEDIUM 

In the end enumeration serves as a wonderful way to keep things organized and give another level of customization.

Java;Notes - 10.) Java Parenthesis and Operator Hierarchy

Just like in math Java has a certain order in which things must be done. Remember the phrase from algebra: "Do whats in parenthesis first" the same rule almost applies to Java only its more or less relative to how the code is formatted and how the program will read it. Here is another nice little chart to look at that explains the following:



Basically what this means is that: a && b || c would actually in code be along the lines of: (a && b) || c and so on down the line.

Java;Notes - 9.) Conversions between Numeric Types

This next part is better shown with a graph.

  • Solid lines indicate conversions that will not lose precision in the numbers
  • Dashed lines will lose some precision if converted.

So if you take int: 123456789 and you want to make it into a "Float" all you need to do is
  • int n = 123456789
  • float f = n  

This will cause the final outcome to take 123456789 and turn it into 1.23456792E8 Notice everything is accurate up to seven?

Lastly a few rules to keep in mind:
  • If either of the operands is of type double, the other one will be converted to a double.
  • Otherwise, if either of the operands is of type float, the other one will be converted to a float.
  • Otherwise, if either of the operands is of type long, the other one will be converted to a long.
  • Otherwise both operands will convert to an int.
Java Casts:
As we learned in the above made section you can convert an integer to a double now it stands to reason that you might sometimes want to convert a double back to an integer. Java adds a thing called "Cast" into mix. Casts are used anytime you want to do a conversion that will result in loss of accuracy. The syntax for it is simple like so:
  1. double x = 9.9998
  2. int nx = (int) x; 
This should print out: 9 as the result when nx is called in a print statement here is the proof:

Rounding numbers up:
If you wish to round a double to its next best option the syntax for that is simple as well:

  1. double x = 9.9998
  2. int nxr = (int) Math.round(x); 
The following image shows the code and the output:

Well that is all I have for this round! Thanks for tuning in!

Java;Notes - 8.) Java Mathematics Functions

Java has a nifty little built in math function library that if you want to use with out typing the whole Math.functionHere you can simply import the following line:
  • import static java.lang.Math.*;
Doing this will make it so you no longer have to type out the full function so instead of doing Square Roots like: "Math.sqrt" you would simply just use "sqrt" Since we are on the topic of diffrent kinds of math operations lets take a look at what else java can offer us:
  • Math.pow (For raising the power of a number)
  • Math.sin
  • Math.cos
  • Math.tan
  • Math.atan
  • Math.atan2
  • Math.exp
  • Math.log
  • Math.log10
  • Math.PI
  • Math.E
Most of these we have run into in math class and we know what they mean so no real explanation needs to be given to the list.