Monday 29 August 2011

the java part 25

If you don't know how many items are going to be held in your array, you may be better off using something called an ArrayList. An ArrayList is a dynamic data structure, meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array.
To set up an ArrayList, you first have to import the package from the java.util library:
import java.util.ArrayList;
You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( );
Notice that you don't need any square brackets this time.
Once you have a new ArrayList objects, you can add elements to it with the add method:
listTest.add( "first item" );
listTest.add( "second item" );
listTest.add( "third item" );
listTest.add( 7 );
In between the round brackets of add you put what it is you want to add to the ArrayList. You can only add objects, however. The first three items we've added to the list above are String objects. The fourth item is a number. But this will be a number object of type Integer, rather than the primitive data type int.
Items in the list can be referenced by an Index number, and by using the get method:
listTest.get( 3 )
This line will get the item at Index position 3 on the list. Index numbers start counting at zero, so this will be the fourth item.
You can also remove items from an ArrayList. You can either use the Index number:
listTest.remove(2);
Or you can use the value on the list:
listTest.remove( "second item" );
Removing an item will resize the ArrayList, so you have to be careful when trying to get an item on the list when using its Index number. If we've removed item number 2, then our list above will contain only 3 items. Trying to get the item with the Index number 3 would then result in an error.
To go through each item in your ArrayList you can set up something called an Iterator. This class can also be found in the java.util library:
import java.util.Iterator;
You can then attach your ArrayList to a new Iterator object:
Iterator it = listTest.iterator( );
This sets up a new Iterator object called it that can be used to go through the items in the ArrayList called listTest. The reason for using an Iterator object is because it has methods called next and hasNext. You can use these in a loop:
while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}

The method hasNext returns a Boolean value. The value will be false if there are no more items in the ArrayList. The next method can be used to go through all the items in the list.
To test all this theory out, try the following code:
Java code showing an array list
Notice the line that prints out the entire list:
System.out.println( "Whole list=" + listTest );
This gives you a quick way to see which items are on your list, if it gets a bit too long.
When the code is run, the Output window will display the following:
first item
second item
third item
7
Whole list=[first item, third item, 7]
Position 1=third item
To sum up, then, use an ArrayList when you're not sure how many elements are going to be in a list of items.

We'll leave arrays, for now, and move on. In the next section, we'll tackle strings.

the java part 24

The arrays you have been using so far have only held one column of data. But you can set up an array to hold more than one column. These are called multi-dimensional arrays. As an example, think of a spreadsheet with rows and columns. If you have 6 rows and 5 columns then your spreadsheet can hold 30 numbers. It might look like this:
A representation of a 2-dimensional array
A multi dimensional array is one that can hold all the values above. You set them up like this:
int[ ][ ] aryNumbers = new int[6][5];
They are set up in the same way as a normal array, except you have two sets of square brackets. The first set of square brackets is for the rows and the second set of square brackets is for the columns. In the above line of code, we're telling Java to set up an array with 6 rows and 5 columns. To hold values in a multi-dimensional array you have to take care to track the rows and columns. Here's some code to fill the first rows of numbers from our spreadsheet image:
aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[0][3] = 11;
aryNumbers[0][4] = 22;
So the first row is row 0. The columns then go from 0 to 4, which is 5 items. To fill the second row, it would be this:
aryNumbers[1][0] = 20;
aryNumbers[1][1] = 45;
aryNumbers[1][2] = 56;
aryNumbers[1][3] = 1;
aryNumbers[1][4] = 33;
The column numbers are the same, but the row numbers are now all 1.
To access all the items in a multi-dimensional array the technique is to use one loop inside of another. Here's some code to access all our number from above. It uses a double for loop:
Java code showing how to use two for loops with a 2-dimensional array
The first for loop is used for the rows; the second for loop is for the columns. The first time round the first loop, the value of the variable i will be 0. The code inside of the for loop is another loop. The whole of this second loop will be executed while the value of the variable i is 0. The second for loop use a variable called j. The i and the j variables can then be used to access the array.
aryNumbers[ i ][ j ]
So the two loop system is used to go through all the values in a multi-dimensional array, row by row.

Exercise
Finish off the programme above where we are writing a programme to print out all the values from the spreadsheet. Your Output window should look something like this when you're done:
Output window of array code
Multi-dimensional arrays can be quite tricky, but mainly because it's hard to keep track of all your rows and columns! In the next part, you'll learn about array lists.

the java part 23

You can place strings of text into arrays. This is done in the same way as for integers:
String[ ] aryString = new String[5] ;
aryString[0] = "This";
aryString[1] = "is";
aryString[2] = "a";
aryString[3] = "string";
aryString[4] = "array";
The code above sets up a string array with 5 positions. Text is then assigned to each position in the array.
Here's a loop that goes round all the positions in the array, printing out whatever is at each position:
int i;
for ( i=0; i < aryString.length; i++ ) {
System.out.println( aryString[i] );
}

The loop goes round and round while the value in the variable called i is less than the length of the array called aryString.
When the above programme is run, the Output window will look like this:
Output window showing the results of a java string array
You can perform a sort on string arrays, just like you can with integers. But the sort is an alphabetical ascending one, meaning that "aa" will come first over "ab". However, Java uses Unicode characters to compare one letter in your string to another. This means that uppercase letter will come before lowercase ones. Try the following code:
Sorting a java string array
When the programme is run, the Output window will display the following:
Unexpected results in the output window
Although we've sorted the array, the word "This" comes first. If this were an alphabetical sort, you'd expect the word "a" to come first." And it does if all the letters are lowercase. In your programming code, change the capital "T" of "This" to a lowercase "t". Now run your programme again. The Output window will now display the following:
Alphabetic sort
As you can see, the word "this" is now at the bottom. We'll have a closer look at strings in the next section, so don't worry too much about them now. Instead, try these exercises.

Exercise
Set up an array to hold the following values, and in this order: 23, 6, 47, 35, 2, 14. Write a programme to get the average of all 6 numbers. (You can use integers for this exercise, which will round down your answer.)
Exercise
Using the above values, have your programme print out the highest number in the array.
Exercise
Using the same array above, have your programme print out only the odd numbers.


In the next lesson, you'll learn about multi-dimensional arrays in java.

the java part 22

Other inbuilt java methods allow you to sort your arrays. To use the sort method of arrays, you first need to reference a Java library called Arrays. You do this with the import statement. Try it with your aryNums programme. Add the following import statement:
import java.util.Arrays;
You code should look like ours below:
Importing the Arrays library
Now that you have imported the Arrays library, you can use the sort method. It's quite easy:
Arrays.sort( aryNums );
First you type the word "Arrays", then a dot. As soon as you type a dot, NetBeans will display a list of things you can do with arrays. Type the word "sort". In between a pair of round brackets, you then put the name of the array you want to sort. (Notice that you don't need any square brackets after the array name.)
And that's it - that's enough to sort the array! Here's some code to try out:
Java code showing how to sort an array
The for loop at the end will go round and round printing out the values in each array position. When the code is run, the Output will look like this:
Output window showing the results of the sort
As you can see, the array has been sorted in ascending order.
Sorting in descending order, however, is only possible either by writing your own sorting code, or converting your array to Integer objects then importing from the Collections library. If you need to a descending sort, here's some code that does just that (skip this code, if you want):

Java code for a descending array sort
All a bit messy, I'm sure you'll agree!

In the next lesson, we'll take a look at arrays and strings.

the java part 21

Arrays come into their own with loops. You have seen in the previous section that to assign values to array positions, you did this:
aryNums[0] = 10;
But that's not terribly practical if you have a lot of numbers to assign to an array. As an example, imagine a lottery programme that has to assign the numbers 1 to 49 to positions in an array. Instead of typing a long list of array positions and values you can use a loop. Here's some code that does just that:
A Java array used in a loop
So we set up an array to hold 49 integer values. Then comes the loop code. Notice the end condition of the loop:
i < lottery_numbers.length
Length is a property of array objects that you can use to get the size of the array (how many positions it has). So this loop will keep going round and round while the value in the variable i is less than the size of the array.
To assign values to each position in the array, we have this line:
lottery_numbers[i] = i + 1;
Instead of a hard-code value between the square brackets of the array name, we have the variable called i. This increases by 1 each time round the loop, remember. Each array position can then be accessed just by using the loop value. The value that is being assigned to each position is i + 1. So again, it's just the incremented loop value, this time with 1 added to it. Because the loop value is starting at 0, this will give you the numbers 1 to 49.
The other line in the loop just prints out whatever value is in each array position.
(If you wanted, you could then write code to jumble up the numbers in the array. Once you have jumbled up the values, you could then take the first 6 and use them as the lottery numbers. Write another chunk of code that compares a user's 6 numbers with the winning numbers and you have a lottery programme!)
In the next part, you'll see how to sort your arrays.

the java part 20

A programming concept you just have to get used to if you're to code effectively is the array. In this section, you'll learn what arrays are, and how to use them.

What is an Array?

So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number, and the string variables just one long string of text. An array is a way to hold more than one value at a time. It's like a list of items. Think of an array as the columns in a spreadsheet. You can have a spreadsheet with only one column, or lots of columns. The data held in a single-list array might look like this:
A representation of an array
Like a spreadsheet, arrays have a position number for each row. The positions in an array start at 0 and go up sequentially. Each position in the array can then hold a value. In the image above array position 0 is holding a value of 10, array position 1 is holding a value of 14, position 2 has a value of 36, and so on.
To set up an array of number like that in the image above, you have to tell Java what kind of data is going in to your array (integers, strings, boolean values, etc). You then need to say how many positions the array has. You set them up like this:
int[ ] aryNums;
The only difference between setting up a normal integer variable and an array is a pair of square brackets after the data type. The square brackets are enough to tell Java that you want to set up an array. The name of the array above is aryNums. Just like normal variables, you can call them almost anything you like (with the same exceptions we mentioned earlier).
But this just tells Java that you want to set up an integer array. It doesn't say how many positions the array should hold. To do that, you have to set up a new array object:
aryNums = new int[6];
You start with your array name, followed by the equals sign. After the equals sign, you need the Java keyword new, and then your data type again. After the data type come a pair of square brackets. In between the square brackets you need the size of the array. The size is how many positions the array should hold.
If you prefer, you can put all that on one line:
int[ ] aryNums = new int[6];
So we are telling Java to set up an array with 6 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 6 positions will be zero ( 0 ).
To assign values to the various positions in an array, you do it in the normal way:
aryNums[0] = 10;
Here, a value of 10 is being assigned to position 0 in the array called aryNums. Again, the square brackets are used to refer to each position. If you want to assign a value of 14 to array position 1, the code would be this:
aryNums[1] = 14;
And to assign a value of 36 to array position 2, it's this:
aryNums[2] = 36;
Don't forget, because arrays start at 0, the third position in an array has the index number 2.
If you know what values are going to be in the array, you can set them up like this instead:
int[ ] aryNums = { 1, 2, 3, 4 };
This method of setting up an array uses curly brackets after the equals sign. In between the curly brackets, you type out the values that the array will hold. The first value will then be position 0, the second value position 1, and so on. Note that you still need the square brackets after int, but not the new keyword, or the repetition of the data type and square brackets. But this is just for data types of int values, string, and char values. Otherwise, you need the new keyword. So you can do this:
String[ ] aryStrings = {"Autumn", "Spring", "Summer", "Winter" };
But not this:
boolean[ ] aryBools = {false, true, false, true};
To set up a boolean array you still need the new keyword:
boolean[ ] aryBools = new boolean[ ] {false, true, false, true};
To get at the values held in your array, you type the name of the array followed by an array position in square brackets. Like this:
System.out.println( aryNums[2] );
The above code will print out whatever value is held at array position 2 in the array called aryNums. But let's get some coding practice.
Start a new project and call it anything you like. Don't forget to change the name of the Class to something relevant.
Type the following code into your new Main method:
Code showing a Java Array
When you run the programme you should see this in the Output window:
Output of the array code
Change the array position number in the print line from 2 to 5 and 18 should print out instead.
In the next part, we'll take a look at how to use arrays with loops.

the java part 19

Another type of loop you can use in Java is called the while loop. While loops are a lot easier to understand than for loops. Here's what they look like:
while ( condition ) {
}
So you start with the word "while" in lowercase. The condition you want to test for goes between round brackets. A pair of curly brackets comes next, and the code you want to execute goes between the curly brackets. As an example, here's a while loop that prints out some text (Try the code out for yourself):
int loopVal = 0;
while ( loopVal < 5) {
System.out.println("Printing Some Text");
loopVal++;
}

The condition to test is between the round brackets. We want to keep looping while the variable called loopVal is less than 5. Inside of the curly brackets our code first prints out a line of text. Then we need to increment the loopVal variable. If we don't we'll have an infinite loop, as there is no way for loopVal to get beyond its initial value of 0.
Although we've used a counter (loopVal) to get to the end condition, while loops are best used when you don't really need a counting value, but rather just a checking value. For example, you can keep looping while a key on the keyboard is not pressed. This is common in games programme. The letter "X" can pressed to exit the while loop (called the game loop), and hence the game itself. Another example is looping round a text file while the end of the file has not been reached.

Do ... While

Related to the while loop is the do … while loop. It looks like this:
int loopVal = 0;
do {
System.out.println("Printing Some Text");
loopVal++;
}
while (
loopVal < 5 );
Again, Java will loop round and round until the end condition is met. This time, the "while" part is at the bottom. But the condition is the same - keep looping while the value inside of the variable called loopVal is less than 5. The difference between the two is the code between the curly brackets of do … while will get executed at least once. With the while loop, the condition could already be met. Java will then just bail out of your loop, and not even execute your curly bracket code. To test this out, try the while loop first. Change the value of your loopVal variable to 5, and then run the code. You should find that the text doesn't get printed. Now try the do loop with a value of 5 for loopVal. The text will print once and then Java will bail out of the loop.

OK, we'll leave looping there. It is a subject you need to get grips with. But don't worry if you're not completely perfect with them - you'll learn as we go along. In the next section, we'll take a look at something called an array.

the java part 18

As we mentioned earlier, the programming you are doing now is sequential programming. This means that flow is downward, from top to bottom, with every line of code being executed, unless you tell Java otherwise.
You saw in the last section that one way to "tell" Java not to execute every line is by using IF Statement to section off areas of code.
Another way to interrupt the flow from top to bottom is by using loops. A programming loop is one that forces the programme to go back up again. If it is forced back up again you can execute lines of code repeatedly.
As an example, suppose you wanted to add up the numbers 1 to 10. You could do it quite easily in Java like this:
int addition = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
But you wouldn't really want to use that method if you needed to add up the numbers 1 to a 1000. Instead, you can use a loop to go over a line of code repeatedly until you've reached 1000. Then you can exit the loop and continue on your way.

Java For Loops

We'll start with For Loops, one of the most common types of loops. The "For" part of "For Loop" seems to have lost its meaning. But you can think of it like this: "Loop FOR a set number of times." The structure of the For Loop is this:
for ( start_value; end_value; increment_number ) {
//YOUR_CODE_HERE
}
So after the word "for" (in lowercase) you have a pair of round brackets. Inside of the round brackets you need three things: the start value for the loop, the end value for the loop, and a way to get from one number to another. This is called the increment number, and is usually 1. But it doesn't have to be. You can go up in chunks of 10, if you want.
After the round brackets you need a pair of curly brackets. The curly brackets are used to section off the code that you want to execute repeatedly. An example might clear things up.
Start a new project for this. Call the Project and Class anything you like. (We've called our Project "loops", and the Class "ForLoops"). Now add the following code:

Code showing a java FOR loop
We start by setting up an integer variable, which we've called loopVal. The next line sets up another integer variable. This variable will be used for the end value of the loop, and is set to 11. What we're going to do is to loop round printing out the numbers from 0 to 10.
Inside the round brackets of the for loop, we have this:
loopVal =0; loopVal < end_value; loopVal++
The first part tells Java at what number you want to start looping. Here, we're assigning a value of zero to the loopVal variable. This will be the first number in the loop. The second part uses some conditional logic:
loopVal < end_value
This says "loopVal is less than end_value". The for loop will then keep going round and round while the value inside the loopVal variable is less than the value in the variable called end_value. As long as it's true that loopVal is less than end_value, Java will keep looping over the code between the curly brackets.
The final part between the round brackets of the for loop is this:
loopVal++
What we're doing here is telling Java how to go from the starting value in loopVal to the next number in the sequence. We want to count from 0 to 10. The next number after 0 is 1. loopVal++ is a shorthand way of saying "add 1 to the value in the variable".
Instead of saying loopVal++ we could have wrote this:
loopVal = loopVal + 1
To the right of the equals sign we have loopVal + 1. Java will then add 1 to whatever is currently stored in the loopVal variable. Once it has added 1 to the value, it will store the result inside of the variable to the left of the equals sign. This is the loopVal variable again. The result is that 1 keeps getting added to loopVal. This is called incrementing the variable. It is so common that the shorthand notation variable++ was invented:
int some_number = 0;
some_number++;

The value of some_number will be 1 when the code above is executed. It is the short way of saying this:
int some_number = 0;
some_number = some_number + 1;

To recap then, our for loop is saying this:
Loop Start value: 0
Keep Looping While: Start value is less than 11
How to advance to the end value: Keep adding 1 to the start value
Inside of the curly brackets of the for loop we have this:
System.out.println("Loop Value = " + loopVal);
Whatever is currently inside of the loopVal variable will be printed out, along with some text.
Run your programme and you should see this in the Output window:
Output window showing the results of the java loop
So we've trapped the programme in a loop, and forced it to go round and round. Each time round the loop, 1 gets added to the loopVal variable. The loop keeps going round and round while the value inside of loopVal is less than the value in end_value. Whatever is inside of the loop's curly brackets is the code that will be executed over and over. And that is the whole point of the loop: to execute the curly bracket code over and over.
Here's some code that adds up the numbers 1 to 10. Try it out:
Java loop adding up the numbers 1 to 10
The answer you should get in the Output window is 55. The code itself is more or less the same as the previous for loop. We have the same two variables set up at the top, loopVal and end_value. We also have a third integer variable, which we've called addition. This will hold the value of the 1 to 10 sum.
In between the round brackets of the for loop, it's almost the same as last time: we're looping while loopVal is less than end_value; and we're adding 1 to the loopVal variable each time round the loop (loopVal++). The only difference is that the starting value is now 1 (loopVal=1).
In between the curly brackets, we only have one line of code:
addition = addition + loopVal;
This single line of code adds up the numbers 1 to 10. If you're confused as to how it works, start to the right of the equals sign:
addition + loopVal;
The first time round the loop, the addition variable is holding a value of 0. The variable loopVal, meanwhile, is holding a value of 1 (its starting value). Java will add 0 to 1. Then it will store the result to the variable on the left of the equals sign. Again, this is the addition variable. Whatever was previously being held in the addition variable (0) will be erased, and replaced with the new value (1).
The second time round the loop, the values in the two variables are these (the values are between round brackets):
addition (1) + loopVal (2);

1 + 2 is obviously 3. So this is the new value that will be stored to the left of the equals sign.
The third time round the loop, the new values are these:
addition (3) + loopVal (3);

Java adds the 3 + 3 and stores 6 to the left of the equals sign. It keeps going round and round until the loop ends. The result is 55.
(Notice that our print line is outside of the for loop, after the final curly bracket of the loop.)

Exercise
Change you code so that the loop adds up the numbers 1 to a 100. The answer you should get is 5050.

Exercise
Write a times table programme. The programme should ask a user to input a number. This number is then used as the times table. So if the user enters 10, the 10 times table should be displayed. Your Output window should look something like this, when your programme is run.
Output of a Java Times Tables  programme

Help for this Exercise
Your for loop only needs two lines of code between the curly brackets, and one of those is the print line. You only need a single line to calculate the answers for your times table.
You should already know how to get the number from the user. This can be used in your loop's curly brackets to work out the answer to your multiplication.
Your times table only needs to go from 1 to 10, like ours does in the image above.

Exercise
Use a for loop to print out the odd numbers from 1 to 10. (For the easy way to do this exercise, think about the increment value of the loop, which is the third item between the round brackets.)
One of the hard ways to do the exercise above is by using an operator you haven't yet met - the modulus operator. Modulus is when you divide by a number and keep the remainder. So 10 Mod 3 is 1, because 10 divide by 3 is 3. The remainder is 1, and that's what you keep. The Modulus operator in Java is the percentage sign, rather confusingly. It's used like this:
int remainder;
int total = 10
remainder = total %3

So the number (or variable) you want to divide up goes first. You then type a percentage sign, followed by your divider number. The answer is the remainder.
In the exercise above, you could use 2 as the Mod number, and then use an IF Statement in your for loop to test what the remainder is. (Can you see why 2 should be the Mod number?)

In the next part, we'll take a look at Java while loops.

the java part 17

Another way to control the flow of your programmes is with something called a switch statement. A switch statement gives you the option to test for a range of values for your variables. They can be used instead of long, complex if … else if statements. The structure of the switch statement is this:
switch ( variable_to_test ) {
case value:
code_here;
break;
case value:
code_here;
break;
default:
values_not_caught_above;

}
So you start with the word switch, followed by a pair of round brackets. The variable you want to check goes between the round brackets of switch. You then have a pair of curly brackets. The other parts of the switch statement all go between the two curly brackets. For every value that you want to check, you need the word case. You then have the value you want to check for:
case value:
After case value comes a colon. You then put what you want to happen if the value matches. This is your code that you want executed. The keyword break is needed to break out of each case of the switch statement.
The default value at the end is optional. It can be included if there are other values that can be held in your variable but that you haven't checked for elsewhere in the switch statement.
If all of that is confusing, here's some code to try out. You can either start a new project for this, or just comment out the code you have. A quick way to comment out code in NetBeans is from the toolbar at the top. First, highlight the code you want to comment out. Then click the comment icon:
The Java comment icon on the NetBeans toolbar
But here's the code:
Code demonstrating a Java switch statement
The first thing the code does is to set a value to test for. Again, we've set up an integer variable and called it user. We've set the value to 18. The switch statement will check the user variable and see what's in it. It will then go through each of the case statements in turn. When it finds one that matches, it will stop and execute the code for that case. It will then break out of the switch statement.
Try the programme out. Enter various values for the user variable and see what happens.
Sadly, you can't test for a range of values after case, just the one value. So you can't do this:
case (user <= 18):
But you can do this:
case 1: case 2: case 3: case 4:
So the above line tests for a range of values, from 1 to 4. But you have to "spell out" each value. (Notice where all the case and colons are.)
To end this section on conditional logic, try these exercises.


Exercise
Write a programme that accepts user input from the console. The programme should take a number and then test for the following age ranges: 0 to 10, 11 to 20, 21 to 30, 30 and over. Display a message in the Output window in the following format:
user_age + " is between 21 and 30"
So if the user enters 27 as the age, the Output window should be this:
Output of the Java exercise
If the user is 30 or over, you can just display the following message:
"Your are 30 or over"

Help for this exercise
To get string values from the user, you did this:
String age = user_input.next( );
But the next( ) method is used for strings. The age you are getting from the user has to be an integer, so you can't use next( ). There is, however, a similar method you can use: nextInt( ).

Exercise
If you want to check if one String is the same as another, you can use a Method called equals.
String user_name = "Bill";
if ( user_name.equals( "Bill" ) ) {
//DO SOMETHING HERE
}

In the code above, we've set up a String variable and called it user_name. We've then assigned a value of "Bill" to it. In between the round brackets of IF we have the variable name again, followed by a dot. After the dot comes the word "equals". In between another pair of round brackets you type the string you're trying to test for.
NOTE: When checking if one string is the same as another, they have to match exactly. So "Bill" is different from "bill". The first has an uppercase letter "B" and the second has a lowercase "b".

For this exercise, write a programme that asks a user to choose between four colours: black, white, red, or blue. Use IF … ELSE IF statements to display one of the following messages, depending on which colour was chosen:
BLACK "You must be a Goth!"
WHITE "You are a very pure person"
RED "You are fun and outgoing"
BLUE "You're not a Chelsea fan, are you?"
When your programme ends, the Output window should look like something like this:
Output window showing results of Java  exercise

OK, let's move on and have a look at loops. We'll be upping the pace a bit in this next section, so hang on to your hats!

the java part 16

A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable type for Boolean values:
boolean user = true;
So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ). If you want to check if a variable "has a value of" something, you need two equal signs ( = =).
Try this simple code:
boolean user = true;
if ( user == true ) {
System.out.println("it's true");
}
else {
System.out.println("it's false");
}

So the first IF Statement checks if the user variable has a value of true. The else part checks if it is false. You don't need to say "else if ( user = = false)". After all, if something is not true then it's false. So you can just use else: there's only two choices with boolean values.
The only other conditional operator on our lists is the NOT operator. You can use this with boolean values. Have a look at the following code:
boolean user = true;
if ( !user ) {
System.out.println("it's flase");
}
else {
System.out.println("it's true");
}

It's almost the same as the other boolean code, except for this line:
if ( !user ) {
This time, we have our NOT operator before the user variable. The NOT operator is a single exclamation mark ( ! ) and it goes before the variable you're tying to test. It's testing for negation, which means that it's testing for the opposite of what the value actually is. Because the user variable is set to true then !user will test for false values. If user was set to false then !user would test for true values. Think of it like this: if something is NOT true then what is it? Or if it's NOT false then what?
In the next part, we'll look at Java Switch Statements.

the java part 15

Instead of using two IF Statements, you can use an IF … ELSE Statement instead. Here's the structure of an IF … ELSE statement:
if ( condition_to_test ) {
}
else {

}
The first line starts with if, followed by the condition you want to test for. This goes between two round brackets. Again, curly brackets are used to section off the different choices. The second choice goes after the word else and between its own curly brackets. Here's our code again that checks a user's age:
Java code showing an IF ... Else Statement
So there are only two choices here: either the user is 18 or younger, or the user is older than that. Adapt your code to match that in the image above and try it out. You should find that the first message prints out. Now change the value of the user variable to 20 and run the code again. The message between the ELSE curly brackets should display in the Output window.

IF … ELSE IF

You can test for more than two choices. For example, what if we wanted to test for more age ranges, say 19 to 39, and 40 and over? For more than two choices, the IF … ELSE IF statement can be used. The structure of an IF … ELSE IF is this:
if ( condition_one ) {
}
else if (
condition_two ) {
}
else {

}
The new part is this:
else if ( condition_two ) {
}
So the first IF tests for condition number one (18 or under, for example). Next comes else if, followed by a pair of round brackets. The second condition goes between these new round brackets. Anything not caught by the first two conditions will be caught be the final else. Again, code is sectioned off using curly brackets, with each if, else if, or else having its own pair of curly brackets. Miss one out and you'll get error messages.
Before trying out some new code, you'll need to learn some more conditional operators. The ones you have used so far are these:
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To

Here's four more you can use:
&& AND
|| OR
== HAS A VALUE OF
! NOT

The first one is two ampersand symbols, and is used to test for more than one condition at the same time. We can use it to test for two age ranges:
else if ( user > 18 && user < 40 )
Here, we want to check if the user is older than 18 but younger than 40. Remember, we're trying to check what is inside of the user variable. The first condition is "Greater than 18" ( user > 18 ). The second condition is "Less than 40" ( user < 40). In between the two we have our AND operator ( &&). So the whole line says "else if user is greater than 18 AND user is less than 40."
We'll get to the other three conditional operators in a moment. But here's some new code to try out:

Java code showing an IF ... Else IF Statement
Run your programme and test it out. You should be able to guess what it will print out before running it. Because we have a value of 21 for the user variable the message between the curly brackets of else if will display in the Output window.
Exercise
Change the value of the user variable from 21 to 45. The message for the else section of the code should now display.

You can add as many else if parts as you want. Suppose we wanted to check if the user was either 45 or 50. We can use two of the new conditional operators above. We can check if the user variable "has a value of 45" OR "has a value of 50":
else if (user == 45 || user == 50)
To test if the user variable has a value of something you use two equal signs, with no space between them. Java will test for that value and no other values. Because want to test for the user being 50 as well, we can have another condition in the same round brackets: user == 50. This just says "test if the user variable has a value of 50". In between the two conditions, we have the OR operator. This is two pipe characters, which is just to the left of the letter "z" on a UK keyboard. Again, there's no space between the two. The whole of the line above says "Else if the user has a value of 45 OR the user has a value of 50".
Here's our code with the new else if part:
Java code showing use of conditional operators
Try it out for yourself. Change the value of the user variable to 45 and run your code. Then change it to 50 and run the code again. In both cases the new message should display.
The various conditional operators can be tricky to use. But you're just testing a variable for a particular condition. It's simply a question of picking the right conditional operator or operators for the job.
 


Nested IF Statements

You can nest IF Statements. (This also applies to IF ... ELSE and IF ... ELSE IF statements.) Nesting an IF Statement just means putting one IF Statement inside of another. For example, suppose you want to find out if somebody is younger than 18, but older than 16. You want to display a different message for the over 16s. You start with the first IF Statement:
if ( user < 19 ) {
System.out.println( "18 or younger");
}

To check for over 16, you can place a second IF Statement inside of the one you already have. The format is the same:
if ( user < 19 ) {
if (
user > 16 && user < 19 ) {
System.out.println( "You are 17 or 18");
}
}

So the first IF Statement catches the user variable if it's less than 19. The second IF Statement narrows the user variable down even further, for ages over 16 and under 19. To print different messages, you can have an IF ... ELSE statement instead of the IF Statement above:
if ( user < 19 ) {
if ( user > 16 && user < 19 ) {
System.out.println( "You are 17 or 18");
}
else {
System.out.println( "16 or younger");
}

}
Notice where all the curly brackets are in the code: get one wrong and your programme won't run.
Nested IF Statements can be tricky, but all you're trying to do is to narrow down the choices.

In the next section, you'll about the Boolean variable type.

the java part 14

The programming you're doing now is sequential programming, meaning the code is executed from top to bottom. It's very linear, in that each and every line of code will be read, starting with the first line of code you write and ending at the last line.
But you don't always want your programmes to work like that. Often, you want code to be executed only if certain conditions are met. For example, you might want one message to display if a user is below the age of 18 and a different message if he or she is 18 or older. You want to control the flow of the programme for yourself. You can do this with conditional logic.
Conditional logic is mainly about the IF word: IF user is less than 18 then display this message; IF user is 18 or older then display that message. Fortunately, it's very easy to use conditional logic in Java. Let's start with IF Statements.

IF Statements

Executing code when one thing happens rather than something else is so common in programming that that the IF Statement has been developed. The structure of the IF Statement in Java is this:
if ( Statement ) {
}
You start with the word IF (in lowercase) and a pair of round brackets. You then use a pair of curly brackets to section off a chunk of code. This chunk of code is code that you only want to execute IF your condition is met. The condition itself goes between round brackets:
if ( user < 18 ) {
}
This condition says "IF user is less than 18". But instead of saying "is less than" we use the shorthand notation of the left-pointing angle bracket ( < ). IF the user is less than 18 then we want something to happen, to display a message, for example:
if ( user < 18 ) {
//DISPLAY MESSAGE
}
If the user is not less than 18 then the code between the curly brackets will be skipped, and the programme continues on its way, downwards towards the last line of code. Whatever you type between the curly brackets will only be executed IF the condition is met, and this condition goes between the round brackets.
Before we try this out, another shorthand notation is this symbol >. The right-pointing angle bracket means "greater than". Our IF Statement above can be amended slightly to check for users who are greater than 18:
if ( user > 18 ) {
//DISPLAY MESSAGE
}
The only thing new in this code is the > symbol. The condition now checks for users who are greater than 18.
But the condition doesn't check for people who are exactly 18, just those greater than 18. If you want to check for those who are 18 or over, you can say "greater than or equal to". The symbols for this are the greater than sign ( > ) followed by an equals sign ( = ):
if ( user >= 18 ) {
//DISPLAY MESSAGE
}

You can also check for "less than or equal to" in a similar way:
if ( user <= 18 ) {
//DISPLAY MESSAGE
}
The above code contains a less than symbol ( < ) followed by the equals sign.
Let's try all this out in a simple programme.
Start a new project by clicking File > New Project from the menu bar in NetBeans. You can call your package and class names anything you like. Enter the following code (our package name is conditionallogic and the Class is called IFStatements):
Code showing a Java IF Statement
We've set up an integer variable, and assigned a value of 17 to it. The IF statement checks for "less than 18". So the message between the curly brackets should be printed out.
Run your programme and check it out. (NetBeans has a habit of running the programme in bold text in the Projects window and not the code you have displayed. To run the code in your coding window, right click anywhere in the code. From the menu that appears select Run File.) You should see this in your Output window:
Output window 1
Now change the value for the user variable from 17 to 18. Run your programme again. You should see this:
Output window 2
So the programme runs OK, with no error messages. It's just that nothing gets printed out. The reason is that the message code is between the curly brackets of the IF Statement. And the IF Statement is checking for values less than 18. IF the condition is not met, Java ignores the curly brackets altogether and moves on.
Exercise
Replace your "less than" symbol with the "less than or equal to" symbols. Change your message to suit, something like "user is less than or equal to 18". Run your programme again. Do you see the message?

Exercise
Change the user value to 20. Run your programme again. Do you still see the message?

You can have more than one IF Statement in your code. Try the following code:
Two IF Statements
This time, we have two IF Statements. The first tests for values less than or equal to 18. The second tests for values greater than 18. When the code is run with a value of 18 or less for the user variable, the Output is this:
Output window 3
Changing the value of the user variable to 20 gives this:
Output window 4
So only one of the IF Statements will Output a print line. And it all depends on what the value of the user variable is.

In the next part, we'll continue with Conditional Logic

the java part 13

Another useful class for accepting user input, and displaying results, is the JOptionPane class. This is located in the javax.swing library. The JOptionPane class allows you to have input boxes like this one:
A JOptionPane Input box
And message boxes like this:
A JOptionPane message box
Let's adapt our code from the previous section and have some option panes.
The first thing to do is to reference the library we want to use:
import javax.swing.JOptionPane;
This tells java that we want to use the JOptionPane class, located in the javax.swing library.
You can start a new project for this, if you prefer not to adapt your previous code. (You should know how to create a new project by now. Just remember to change the name of the Class from Main to something else. We're going to have the class name InputBoxes for ours. Our package name will be userinput.)
Add the import line to your new project, and your code window should look like something like this:
A JOptionPane import line
(The reason for the wavy underline is that we haven't used the JOptionPane class yet. It will go away once we do.)
To get an input box that the user can type into, we can use the showInputDialog method of JOptionPane. We'll store the input straight into a first name variable again, just like last time. So add the following line to your main method:
String first_name;
first_name = JOptionPane.showInputDialog("First Name");

As soon as you type a full stop after JOptionPane you will see the following popup list:
A list of available methods for JOptionPane
Double click showInputDialog. In between the round brackets of showInputDialog type the message that you want displayed above the input text box. We've typed "First name". Like all strings, it needs to go between double quotes.
Add the following code so that we can get the user's family name:
String family_name;
family_name = JOptionPane.showInputDialog("Family Name");

Join the two together, and add some text:
String full_name;
full_name = "You are " + first_name + " " + family_name;

To display the result in a message box, add the following:
JOptionPane.showMessageDialog( null, full_name );
This time, we want showMessageDialog from the popup list. In between the round brackets we first have the word null. This is a java keyword and just means that the message box is not associated with anything else in the programme. After a comma comes the text we want to display in the message box. The whole of your code should look like this:
Some Java code using JOptionPane
Notice the line at the bottom of the code:
System.exit(0);
As its name suggests, this ensures that the programme exits. But it also tidies up for us, removing all the created objects from memory.
Now run your code. (Another quick way to run your programme in NetBeans is by right-clicking anywhere inside of the coding window. From the menu that appears, select Run File.)
You'll see the First Name input box. Type something into it, then click OK:
Message Box 1
When the Family Name input box appears, type a family name and click OK:
Message Box  2
After you click OK, the message box will display:
Message Box 3
Click OK to end the programme.

Exercise
Input boxes and Message boxes can be formatted further. Try the following for your Input boxes:
showInputDialog("First Name", "Enter Your First Name");
showInputDialog("Family", "Enter Your Family Name");

Exercise
For your Message boxes try this (yours should be on one line):
showMessageDialog(null, full_name, "Name", JOptionPane.INFORMATION_MESSAGE);

Exercise
Instead of JOptionPane.INFORMATION_MESSAGE try these:
ERROR_MESSAGE
PLAIN_MESSAGE
QUESTION_MESSAGE
WARNING_MESSAGE
Exercise
Input boxes are not just used for text: they can accept numbers as well. Write a programme that prompts the user for two numbers, the breadth of a rectangle and the height of a rectangle. Use a message box to calculate the area of the rectangle. (Remember: the area of a rectangle is its breadth multiplied by the height.) However, you'll need some extra help for this exercise.

Help for the Exercise
You have to use the String variable to get your numbers from the user:
String breadth;
breadth = JOptionPane.showInputDialog("Rectangle Breadth");

However, you can't multiply two strings together. You need to convert the Strings to integers. You can convert a string to an integer like this:
Integer.parseInt( string_to_convert )
So you type Integer then a full stop. After the stop, type parseInt( ). In between the round brackets of parseInt, type the name of the string variable you're trying to convert.
Set up an int variable for the area. You can then multiply and assign on the same line;
int area = Integer.parseInt( string_one ) * Integer.parseInt( string_two);
For the message box, use concatenation:
"answer = " + area
You can use any of the MESSAGE symbols for your message box.

Exercise
The programme will crash if you enter floating point values for the breadth and height. How would you solve this?
When you have solved the above exercise, do you really want Integer.parseInt? What else do you think you can use?

OK, we'll move on now. Let's try some IF statements.

the java part 12

One of the strengths of Java is the huge libraries of code available to you. This is code that has been written to do specific jobs. All you need to do is to reference which library you want to use, and then call a method into action. One really useful class that handles input from a user is called the Scanner class. The Scanner class can be found in the java.util library. To use the Scanner class, you need to reference it in your code. This is done with the keyword import.
import java.util.Scanner;
The import statement needs to go just above the Class statement:
import java.util.Scanner;
public class StringVariables {

}

This tells java that you want to use a particular class in a particular library - the Scanner class, which is located in the java.util library.
The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of code. It doesn't do anything until you create a new object from it.)
To create a new Scanner object the code is this:
Scanner user_input = new Scanner( System.in );
So instead of setting up an int variable or a String variable, we're setting up a Scanner variable. We've called ours user_input. After an equals sign, we have the keyword new. This is used to create new objects from a class. The object we're creating is from the Scanner class. In between round brackets we have to tell java that this will be System Input (System.in).
To get the user input, you can call into action one of the many methods available to your new Scanner object. One of these methods is called next. This gets the next string of text that a user types on the keyboard:
String first_name;
first_name = user_input.next( );

So after our user_input object we type a dot. You'll then see a popup list of available methods. Double click next and then type a semicolon to end the line. We can also print some text to prompt the user:
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next( );

Notice that we've used print rather than println like last time. The difference between the two is that println will move the cursor to a new line after the output, but print stays on the same line.
We'll add a prompt for a family name, as well:
String family_name;
System.out.print("Enter your family name: ");
family_name = user_input.next( );

This is the same code, except that java will now store whatever the user types into our family_name variable instead of our first_name variable.
To print out the input, we can add the following:
String full_name;
full_name = first_name + " " + family_name;


System.out.println("You are " + full_name);
We've set up another String variable, full_name. We're storing whatever is in the two variables first_name and family_name. In between the two, we've added a space. The final line prints it all out in the Output window.
So adapt your code so that it matches that in the next image:
Code showing the use of the Scanner Class
Run your programme until your Output window displays the following:
Output window 1
Java is now pausing until you enter something on your keyboard. It won't progress until you hit the enter key. So left click after "Enter your first name:" and you'll see your cursor flashing away. Type a first name, and then hit the enter key on your keyboard.
After you hit the enter key, java will take whatever was typed and store it in the variable name to the left of the equals sign. For us, this was the variable called first_name.
The programme then moves on to the next line of code:
Output window 2
Type a family name, and hit the enter key again:
Output window 3
The user input has now finished, and the rest of the programme executes. This is the output of the two names. The final result should like this:
Output window 4
So we used the Scanner class to get input from a user. Whatever was typed was stored in variables. The result was then printed to the Output window.
In the next part, we'll take a brief look at Option Panes.

the java part 11

As well as storing number values, variables can hold text. You can store just one character, or lots of characters. To store just one character, the char variable is used. Usually, though, you'll want to store more than one character. To do so, you need the string variable type.
Start a new project for this by clicking File > New Project from the menu bar at the top of NetBeans. When the New Project dialogue box appears, make sure Java and Java Application are selected:
The New Project dialogue box
Click Next and type StringVars as the Project Name. Make sure there is a tick in the box for Create Main Class. Then delete Main after stringvars, and type StringVariables instead, as in the following image:
Renaming the project and the class
So the Project Name is StringVars, and the Class name is StringVariables. Click the Finish button and your coding window will look like this (we've deleted all the default comments). Notice how the package name is all lowercase (stringvars) but the Project name was StringVars.
Blank java coding window
To set up a string variable, you type the word String followed by a name for your variable. Note that there's an uppercase "S" for String. Again, a semicolon ends the line:
String first_name;
Assign a value to your new string variable by typing an equals sign. After the equals sign the text you want to store goes between two sets of double quotes:
first_name = "William";
If you prefer, you can have all that on one line:
String first_name = "William";
Set up a second string variable to hold a surname/family name:
String family_name = "Shakespeare";
To print both names, add the following println( ):
System.out.println( first_name + " " + family_name );
In between the round brackets of println, we have this:
first_name + " " + family_name
We're saying print out whatever is in the variable called first_name. We then have a plus symbol, followed by a space. The space is enclosed in double quotes. This is so that Java will recognise that we want to print out a space character. After the space, we have another plus symbol, followed by the family_name variable.
Although this looks a bit messy, we're only printing out a first name, a space, then the family name. Your code window should look like this:
Some simple Java Strings
Run your programme and you should see this in the Output window:
Output of the String code
If you are storing just a single character, then the variable you need is char (lowercase "c"). To store the character, you use single quotes instead of double quotes. Here's our programme again, but this time with the char variable:
Some code showing the Char variable type
If you try to surround a char variable with double quotes, NetBeans will underline the offending code in red, giving you "incompatible type" errors. You can, however, have a String variable with just a single character. But you need double quotes. So this is OK:
String first_name = "W";
But this is not:
String first_name = 'W';
The second version has single quotes, while the first has double quotes.
There are lot more to strings, and you'll meet them again later. For now, let's move on and get some input from a user.