Sunday, July 17, 2016

JAVA Loop Statements




Loops allow for simplified coding when you want to perform the same task over and over again.


For example, you may want to create a print out of an integer value counting down from 10 to 0. Instead of writing a print command 10 times you can use a loop that will run through a single print command ten times, and update the integer value automatically.


for ( int i = 10; i >= 1; i = i -1 ) {
out.println("Countdown" + i );
}


The for loop statement contains 4 parts

int i = 10; is the initialization of the variables in the loop

i>=1;  is the test condition for the loop, as long as this condition is true the loop will continue to execute

i=i-1 is the update instruction, the variable value will be updated at the conclusion of each execution of the loop

{out.println("Countdown" + i);} is the body of the loop everything within the {} is executed as long as the loop condition allows


Common Loop Coding Errors


Don't put a semicolon ; immediately after the for statement:

for ( int i = 10; i >= 1; i = i -1 ) ; {
out.println("Countdown" + i );
}

The loop statement will end after the ; and won't run through the execution of the body of the text



Don't create an update statement that doesn't update the variable


for ( int i = 10; i >= 1; i = i-- ) {
out.println("Countdown" + i );
}

Improper use of the shortcuts i-- and i++ , these do not change the original value of the variable, use ++i and --i instead


Don't create a conditional statement that is false under the initialization value

for ( int i = 10; i <= 1; i = i -1 ) {
out.println("Countdown" + i );
}

If the initial value of the variable results in a false condition statement the loop will not execute anything




Nested For Loops


You can write loops inside of other loops when needing to run through multiple variable updates at the same time.

For example, you can use the Countdown loop and add another loop to print out a variable's value that increases by 1/10 every time the countdown progresses:


for ( int i = 10; i >= 1; i = i -1 ) {

for (double j = 0.1; j<=1; j=j+0.1) {
out.println(j + " seconds" );
}

out.println("Countdown" + i );
}

The nested loop needs to use a different variable name so that it will not interfere with the outer loop's function


Do not use the wrong variable in the test condition statement



for ( int i = 10; i >= 1; i = i -1 ) {

for (double j = 0.1; i<=1; j=j+0.1) {
out.println(j + " seconds" );
}

out.println("Countdown" + i );
}


If the wrong variable is called in the inner loop you may run an infinite loop - the variable i does not update inside the inner j-loop

Do not use the wrong update variable




for ( int i = 10; i >= 1; i = i -1 ) {

for (double j = 0.1; j<=1; i=i+0.1) {
out.println(j + " seconds" );
}

out.println("Countdown" + i );
}


If you update the wrong variable you may get results that you do not expect, or run the risk of running an infinite loop






Indefinite Loops


If you want to create a loop that has an unknown number of iterations or allows for a user to input data controlling the number of loop iterations you can use an indefinite while or do while loop.


The format for the while loop looks like this:


int n=0;

while(n<=100) {
n=n+5;
out.println(n);
}


The do while loop is best used when you know the loop will be executed at least once:



int n=0;

do{
out.println(n);
n=n+1;
}while(n<=100);



You can use while or do while loops in the place of for loops whenever you choose, you can experiment with these options to optimize your code for space and simplicity.



Loops and the Random Number Generator Class


Random numbers are an important mathematical tool for solving lots of complex world problems. You can also simulate a random input such as a role of a dice for gaming purposes. Generating random data is a common step for statistical models and can be done easily in JAVA with the Random Class.


The Random Class is most commonly used with loops to generate and store many random numbers at once with a simple set of code instructions:


import java.util.Random;  //imports the JAVA Random Class

Random rand = new Random();  //creates a random object called rand

int random_Integer = rand.nextInt();  //initializes a variable


do{
out.println(random_Integer);
random_Integer = rand.nextInt();
}while(random_Integer!=1);




Common Random Methods

random_Integer = rand.nextInt();

random_Integer_below_Max = rand.nextInt(100);

random_Double = rand.nextDouble();  (range returned between 0.0 and 1.0)




Tuesday, July 5, 2016

JAVA If Statements


If statements allow you to run one set of code if a certain condition is met, and another set of code if another condition is met


For example, you may want to write a piece of code that only prints the output of a value less than 1, or if you want to add together two numbers only if they are positive

The basic format of the if statement looks like this:

if (test condition) {
statements if true;
}
statements;

The final statements are run regardless of the if statement (they are outside the {} ) the first set of statements are executed only if the test condition is met

Test Conditions


Test Conditions are boolean expressions (results in either "True" or "False") that typically use relational operators like:


==     equals
!=      not equal
>       greater than
<       less than
>=     greater than or equal to
<=     less than or equal to

The && operator can be used to combine 2 test conditions together

int x = 10;

if(x<20) && (x>1) {
x=x+10;
}

In this example the value of x is tested to see if it is less than 20 AND greater than 1 before it will execute the +10 addition, both conditions must be true

Logical Operators that can be used include:

&&     And     (x<20) && (x >1)

||       Or       (x>5) || (x==2)

!        Not       !(x==10)



Stacking If Statements


Sometimes it is necessary to stack if statements in order to get the proper result

In this example, the correct table size is selected based on the number of people attending



if (people <= 2) {
tableSize="3feet x 3feet";
          } else if  (people<=6){
              tableSize="3feet x 6feet";
                     } else if (people <=8) {
                        tableSize="3feet x 9feet";
                               } else { tableSize="There are too many people"
                               }



The else statement can be used to join if statements together in a group, as soon as a conditional if statement is met the program stops continuing on to the next stack in the series, this can be a great time saver


           

Questions to consider when constructing if statements

How many different outcomes are possible?

Is there a need for output when none of the included conditional statements are true?

Can you combine conditional statements to get the right answer faster?

Are there redundant conditional statements?

JAVA Methods

In JAVA you can create your own methods and Classes to perform actions that are not currently built into the JAVA language (ie Math.max , .substring, Character.toUpperCase)


method: a group of statements that we give a unique name



Methods can reduce redundancy in your code and setup a clean structure for your code that is easier to modify or debug

There are two type of methods -


static methods: not associated with objects, they are helper functions (ie Math Class and Character Class methods)


member methods: are associate with some object type and work on the data in the object (ie String Class methods)


Creating Static Methods


The syntax for creating static methods looks like -


public static return_type name(parameters)  { 
statement;
statement;
statement;
...
statement;
}

public indicates that anyone can use this method

If there is no return type enter void  

If there are no parameters then the parentheses is left empty ()

When a method is called the program execution jumps to that method, performs the associated statements, then jumps back to the call location to continue the code execution

Parameters

Parameters are passed to a method by the caller (ie numbers given to the Math.max method, or character given to the  Character.toUpperCase method)

When you create your method, you need to declare the type and variable name of the parameters that will be used in the method - When the method is called, the parameters get initialized (values assigned)

Declaring parameters is similar to declaring variables (type and name needed)


public static return_type name(type name, type name, ... , type name)  { 
statement;
statement;
statement;
...
statement;
}

Here is an example:


public static void helloWorld(String sayName)  { 
out.println("Hello World my name is " + sayName);
}

When the method helloWorld is called the parameter for the person's name is initialized using a string type parameter

helloWorld("Martha");


Overloading

You can use the same method name for multiple methods as long as there is a difference in the parameters, for example if you want to create a method to calculateAverage, you can create multiple methods for different types (calculating average of 3 integers, 4  integers, 2 doubles, etc.)


Variable Scope

Variables only exist inside the {   }  in which they are declared

Example:


public static void scopeExample() 

double x=0.1;

{
int  y = 25;
out.println(x + " " + y);
}

// variable y no longer exists

}

//variable x no longer exists


Parameter Scope

A parameter exists only inside the method it is declared in

When the method is called the value of the parameter gets assigned to the parameter name - known as call-by-value or pass-by-value

The called parameter value is maintained even if additional functions are applied to it


Method Return Values

The return type is specified in the method declaration as in the example below:


public static int doubleInteger(int paramInteger)  { 

int result = 2 * paramInteger;

return result;

}

The return statement sends a specific value back to the caller and immediately ends the method and returns to the call location





Class Note about the .out object



The .out object used in out.println is not a globally available object - so it will not work inside static methods that want to use it

To fix this simply remove "static" in declaring methods to get access

System.out is a global object and can be used to print to the desktop computer

out is an object that was created to write output to the android app screen

Saturday, July 2, 2016

JAVA String Class



The String Class


String objects contain a sequence of characters plus methods that can operate on the string data

The String Class is called with the format:



objectName.methodName(parameters)




Common String Methods

Combine 2 string elements together and print "combine"

String     value1 = "com";

out.println(value1.concat("bine"));



Extract a substring beginning at the 3rd character and is up to but not including the 7th character to print "stop"

The first character in any string is 0 and counts up from there

String     stringSection = "unstoppable".substring(2,6);

out.println(stringSection);



Return a "True" if the string begins with "in"

"inside".startsWith("in");



Return the # of characters contained in a string

"foreverandever".length();



Returns a position of the beginning of a given string inside of another, returns -1 if it is not found

"where's waldo?".indexOf("waldo");



Create a new string with all lower case letters

"I DON'T KNOW".toLowerCase();



Creates a new string with all Upper Case letters

"happy birthday".toUpperCase();



Returns the character at the given position

"project4".charAt(7);



The Character Class


The type char allows you to store a single character

char uses single quotes 'a', '?', '5'

string use double quotes "hello"

Methods like charAt return a char type output


char     numberPeople = "5 guests".charAt(0);


Each character that can be expressed with a char type also has a number assigned to it called  ASCII/UTF-16 values


'A'  is 65
'B' is 66
'a' is 97
'b' is 98
'*' is 42


Common Character Methods