Sunday, June 26, 2016

JAVA Math Class


The Math Class is JAVA contains many standard mathematical functions or methods

The class does not need to be imported and is called as shown:

Value = Math.Method_Name(Parameters);


Common Math methods:

absolute_Value=Math.abs(-33);

base_to_Exponent=Math.pow(base,exponent);

convert_Degrees_toRadians=Math.toRadians(60);

convert_Radians_toDegrees=Math.toDegrees(1.05);

cos_of_Angle_inRadians=Math.cos(0.52);

Eulers_number=Math.E + 20;

log_Base10=Math.log10(40000);

max_Value=Math.max(6,10,100);

minimum_Value=Math.min(-3,4);

random_Double_between0_and1=Math.random();

round_Down=Math.floor(4.2);

round_Nearest_WholeNumber=Math.round(6.5);

round_Up=Math.ceil(7.9);

sin_of_Angle_inRadians=Math.sin(1.75);

square_Root=Math.sqrt(44);

tan_of_Angle_inRadians=Math.tan(3.05);

Value_of_Pi=Math.PI *2;





Thursday, June 23, 2016

App Basics : Displaying Data to the Screen



When displaying data to a desktop computer screen the object System.out is used. For Android applications, the method is more complicated, the object out will be created to print data to the app screen as shown below:


out.println("Text to Display");

 
println - prints and then advances to the next line
print - prints without advancing to the next line

To display a blank line on the screen just use the format:


out.println();


The text or string you want to display must be contained within the "  " 

The string must be all on the same line

If you want to include " in your screen display they must be preceded by a \


out.println("I am \" INCLUDING \" the quotes");


To include a \ character just use a double \\


out.println("I am including the \\ here");
 

To include a tab use \t

out.println("I am including a tab \t here");
 

To go to a new line in the display add \n


out.println("Next line \n Line 2");


To add the value of a variable use + and the variable name
 
int total_Sum = 35+94;
 
out.println("I have a total of " + total_Sum);
 
out.println("Do you have " + total_Sum + " total?");


Displaying Formatted Data


printf - prints data that is formatted in a specific way

%d    - integer
%f    - a decimal number
%s    - a string
 

%5d    - an integer, 5 characters wide , right aligned
%-3d   - an integer, 3 characters wide, left aligned
%.5f    - a decimal number with 5 characters after the decimal
%7.3f   - a decimal number 7 characters wide, with 3 characters after the .

 
int display_int = 4596;
 
out.printf("I want to display an integer here %4d", display_int);




double display_dec=0.4596;
double display_dec2=0.3596;
 
out.printf(" %.3f percent of the total not %1.4f ", display_dec, display_dec2);


Decimal numbers are rounded if the full # of characters after the decimal is not used

The total width callout is a minimum width requirement, total width/number is not truncated

Monday, June 13, 2016

JAVA Expressions




What is an expression?


Anything that computes to a different value:


This            =            That
Expression 1              Expression 2



An expression can contain different types of mathematical operators - in Java the different operators you can use include:

                                                            +     addition
                                                            -      subtraction
                                                            *     multiplication
                                                            /     division
                                                           %    modulus or remainder
                                                           ()     parentheses


These operators will be dependent on what types of numbers are used, for example if you use only integer-type number variables, then the answer to  7/2 would be  3  (the full answer will not round but be cutoff to the whole number value) if you used floating type number variables the answer would be the full 3.5

The % can be used to obtain the remainder in this case 7/2 = 3 remainder 1 so a 7%2 would return the result of 1

The % can be useful for determining if a value is even or odd or to test if one integer is evenly divisible by another or not.


If a floating point type number (3.5) is combined in an expression with an integer type number the result will be a floating type number.

 
( ) parentheses are used as in standard math formulas to determine the order of operations in an expression


Expression Shortcuts


You can combine a few terms together when you want to update a variable to a new value that includes an operator on itself, for example:

 
cost = cost +1000;       OR        cost  +=  1000;    
 

You can quickly increment a variable by or decrease a variable by one:


minutes = minutes + 1     OR    ++minutes      OR     minutes++
 
minutes = minutes - 1    OR    --minutes    OR    minutes--
 
 


Sunday, June 5, 2016

JAVA Variables and Data Types

 

JAVA Variables

Variables store data that can vary throughout the program run. For example there may be several calculations done in your program where the answer of each calculation is set equal to the variable "x"

3+2 =x
4+6=x
8-2=x

Since each of the possible values for x above must be different, x is a variable, each time a calculation is done the current value of x may change.

Variables can also be set equal to text that changes as you run your program.
 
x = "Going"
x = "Gone"

Every variable in Java has both a name and a type


JAVA Variable Names


The name of a variable must contain only letters (upper and lower case), numbers (0 through 9), and the underscore _ character

The first character of a variable name cannot be a number

The variable name is case-sensitive so consistent use of upper and lowercase letters is a must

The variable names in Java can contain as many characters as you want

Variable names must not match reserved words already used by Java for other functions

x_1
string_x01
Answer_100

Are examples of acceptable variable names


Tip:  Use a Capital letter to begin the name of a Class, use lowercase letters to begin a name of a variable or method

Tip: Make the name meaningful and descriptive to assist in remembering the functionality of the variable



JAVA Variable Types


The type for the variable helps to determine what kind of functions can be performed with that variable 
 

Primitive Java Types


There are 4 number integer types (byte, short, int, and long)
 
      Type int is the most common for integer whole numbers

0
-100
10000


There are 2 floating point number type (float and double)

      Type double is the most common floating point / decimal number type

0.50
-6.75946
5.4e7

Single characters are stored with type char
 
'a'
'#'
'G'

True / False values can be stored with type boolean

true
false

Declaring Variables in Java


You need to type both the variable type and name to declare it in your JAVA code

int amountSpent;

The variables must be declared before you can use them in your code

If you have multiple variables using the same type you can separate them in the declaration using a comma

int numberOfpeople, servingsChicken, servingsBeef, servingsVeggie;
double priceChicken, priceBeef, priceVeggie;

Assigning values to Variables in Java


An assignment statement can be used in your code to assign a value to a variable after it has been declared. Assigning an initial value to a variable is done typically soon after the variable is declared.

numberOfpeople = 45;
 
priceChicken = 4.05 * numberOfpeople ;
 
 

The operation to the right of the equal sign is completed first, then the variable is defined / or redefined as in the example below

                   int counter_one;
                   counter_one=0;                            value is 0
                   counter_one = counter_one +1;     value is 1
                   counter_one = counter_one +1;     value is 2             
 

TODO Comments in Android Studio


 
TODO Statements in Android Studio help the coder to create a list of tasks that need to be done within the code. A few benefits to using TODO statements include:
 
1) When working with a group of people - to help easily identify work that needs
    to be done
 
 
2) Easily trace a section of code that needs to be improved
 
 
3) Identify code that could potentially be done more efficiently
 
 
To add TODO statements to your android code simply create a comment that begins with the // TODO text like the example below.
 
 
// TODO Add More Code Here
 
 
 
Below the Main Editor Window in Android Studio there is a special tracker for all the TODO statements in your code, opening this window will list all the TODO statements and what files they can be found in
 
 
 
 
If you click on the TODO statement in the tab it will take you directly to the file and location where that statement can be found, the tab will also indicate the line # that the statement can be found in the file - you can turn line #'s on in the Main Editor Window by Right-Clicking the Left-Hand Side Bar of the Window and selecting SHOW LINE NUMBERS
 
 


Wednesday, June 1, 2016

Debugging and Logging Basics in Android Studio

Basic Tools for Debugging

When creating your code in Android Studio, you may see indicators of syntax errors resulting from typos, missing punctuation, etc. that will cause your program to fail if you try to run it.

The most basic indicator is a red underline showing up both in the associated file names in the project window as well as in the file code itself in the main editor window where the error occurs.




If the error is something detectable a red dash line will show up to the right of the main editor window near the problem to offer a hint on what may need to be done. In the case below a missing semi-colon is expected at the location of the red underline




Fixing the errors will cause the code to automatically remove the red indicators




Orange colored indicators will represent notifications to be aware of, such as unused or unnecessary code in your program.


Using Logcat

 Another useful tool for debugging your programs is Logcat. By using Logcat to generate a log file of your program while it runs you can:

1)  Keep a record of error messages, notifications, and custom messages

2)  Understand your app's runtime behavior

3)  Filter and organize the log messages


How to Create a Custom Log message in Android Studio


First in the MainActivity.java file include the following line at the top of the file near the other "import" commands


import android.util.Log;

 




A local string variable needs to be created to identify the class where the log messages come from, add the following code in your MainActivity.java file somewhere below and inside the public class MainActivity.



private final static String LOG_TAG = MainActivity.class.getSimpleName ();
 
 
 

 
  
In this example a method called buttonPressed is run to create some display text when a button is pressed on the user interface, the custom log messages will be created here to follow along with the user and program actions




 There are 6 types of log messages or "log levels"


 1) Assert.a  - : Highest severity, if you filter log messages at this level no
                            other log level messages will be displayed
 

 2) Error -    .e  - : Second severity, if you filter log messages at this level only
                                        Assert and Error messages will be displayed


 3) Warn -   .w  - : Third severity, if you filter log messages at this level only
                            Assert, Error, and Warning messages will be displayed


 4) Info    -  .i  - :  Fourth severity, if you filter log messages at this level
                            Assert, Error, Warning, and Info messages display


 5) Debug.d  - : Fifth severity, if you filter log messages at this level all
                            other log level messages except Verbose will display


 6) Verbose.v  - : Sixth severity, if you filter log messages at this level all
                              other log level messages will be displayed



In the example, an Info level log text message is generated with the following code just after the user presses a button to log that the method buttonPressed has begun:



Log.i(LOG_TAG,"buttonPressed(View) Called");
 
 


The next log message is a verbose level and contains both a string of text and the value of a variable, by logging what the current value is of a variable during the program run you can check to make sure that the program is behaving as it should.

The code for this text + variable log message in this example looks like this:



Log.v(LOG_TAG, "text changed to:" + stringValue);



 
 
Finally, a debug level log message is added to the end of the buttonPressed method to log that the method has finished running. The code for this text log looks like this:
 
 
Log.d(LOG_TAG,"buttonPressed(View) finished");
 



How to filter Logcat messages in Android Studio


First you will run your code with your built-in custom log messages. In this example, a button is generated and when the user pushes it, some text is generated. When the program is launched the Android Monitor Window will display your log file.



You can filter the different log message levels by selecting the drop down box under the Logcat tab and selecting the level you wish to filter to. You can also search for keywords in your Logcat file using the search browser in the Logcat tab.




Tip:  It's a good idea to create log messages at the beginning and end of an important process in your code so that if you run it more than once you can easily track when and how many times that process ran