Previous Thread
Next Thread
Print Thread
Rate Thread
#18749 04/05/02 09:19 PM
Joined: Mar 2002
Posts: 562
Le4rner Offline OP
UGN Supporter
OP Offline
UGN Supporter
Joined: Mar 2002
Posts: 562
Pergesu posted this awsome tut on my site. I thought it was something to share. So here it is.

Java Tutorial - Part I

Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)


Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.


Table of Contents
-------------------------
1) Brief intro
2) A little history of Java
3) What can I do with Java?
4) Basic output
a) Hello, world! console
b) Explanation of a class
c) More console output
d) Some graphical output
5) Basic input
6) Wrap up



--------------------------
Section 1
Brief Intro
---------------------------
Welcome to Part I of this Java programming tutorial. This first part is an introduction to Java programming, it will cover only basic stuff. It is mainly to acquaint you with Java's syntax, as well as learn some of the basic functionality of Java. This is really for the novice who has never programmed. If you're already a programmer just learning Java, then just check out the code and read the explanations on whatever confuses you. That said, I hope you learn and enjoy!

---------------------------
Section 2
A little history
---------------------------
In the Middle Ages of Computer Programming (ca. 1989), the Sun Microsystems saw a major problem with the majority of programming languages in use- they weren't easily portable. Code that worked on some processors and OSs didn't work on others without some major changes. There were a few languages, such as C and C++, that did not have to be greatly modified, but had to be modified nonetheless for portability. Sun envisioned a language that would run on every processor type and OS. They figured that they could create some kind of virtual machine that translated programmer code into machine code. Thus, to run a program, the user would only have to have a copy of the virtual machine for their processor and OS.
In 1991, Sun began to take steps toward achieving their vision of the "universal programming language." They funded an internal research project they code-named Green. The resulting language was one that was based on C and C++, and was originally called Oak. However, the creators found that another language was already named Oak, and so at a visit to a local coffee shop, the name Java was suggested. Thus, Java was born.

------------------------------
Section 3
What can I do?
-------------------------------
With Java, you are able to do two main, distinct things- write applets or applications. An application is just a regular program that runs on its own. An applet is generally imbedded into a web page to add extra functionality or entertainment value. A major appeal to Java is its ability to assist in creating dynamic content. Java is also being increasingly used in the development of imbedded systems. You can do everything with Java you can do with most other languages. Graphics, networking, whatever you want.

------------------------------
Section 4
Basic output
------------------------------
If you're like me, you skipped the first few sections to get to the code. Well here ya are...

--------------------------------
Section 4a
Hello, world! console
---------------------------------

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

Cool, so we wrote our first program, just compile and run it. Oh shoot, we don't know how to do that yet. Let's get to it then! First thing to to is run over to http://java.sun.com and download the latest version of the SDK. The SDK contains all the tools you need to compile and run java programs. Read the accompanying documentation to install it, as it's a bit different for every OS. Now install the JDK, and we're set.
Before I explain the code, try compiling and running the the program. To do this, get a command prompt in your favorite OS, and switch on over to the directory that contains Hello.java. Then type

javac Hello.java

Hopefully you didn't get any errors. If so, make sure your code is exactly like mine, and the file name is Hello.java (I'll explain that in a bit). After this command, you will have a file called Hello.class in your directory. This contains the compiled Java code for the virtual machine to execute. If you don't know what the virtual machine is, read Section 2. So we have the Hello.class, then what? Type

java Hello

This should give us the following output:

Hello, world!


Alright, a run-down of the code...

First thing to know is that // signifies a comment. The compiler ignores everything that follows the //. It can appear on the same line as code, as long as it's after the code:
System.out.println("Hello, world!"); // Ouput a message

public class Hello
This line declares a class named Hello. In every Java program you write, you will declare at least one class. public is a keyword saying that it can be used in any program that you or anyone else writes. class, of course, says it's a class. Hello is the name of the class. It's possible to declare more than one class in a file. However, ONLY 1 CLASS MAY BE PUBLIC. This is important to remember. If you have more than one public class in a file, compilation will fail. Also, the name of the public class must also be the name of the file plus .java. Thus, public class MyClass goes in MyClass.java, public class BobsClass in BobsClass.java. If you don't name it like that, it won't compile. So go back up and rename the file Hello.java- that's why you had that problem (I know, I've changed examples around too!).

public static void main(String args[])
This line declares a method called main. For now, just think of methods as blocks of code that allow you to organize your programs better. They will be discussed in great detail later on. void means that the method does not return a value. Every method is called by some other method (with the exception of main()). Methods are able to return values to the methods that called them. This again is unimportant for the time being. main() is a method that gets called automatically when you run your program. Every application class you write must have one method named main(). String argv[] is a parameter to the method. This will also be discussed later. Here, it allows you to call your program with command-line options.

System.out.println("Hello, world!");
This is called a statement. All statements end in a semicolon (;). This just prints out "Hello, world!" without the quotation marks. What you enter between the parentheses is what is displayed. What is between the parentheses is known as a argument. A method can have multiple arguments; when this is the case, they are separated by commas.

---------------------------------
Section 4b
Class explanation
---------------------------------
Take a look at the program again:
// Hello.java
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}

We saw what each line of code does, but you may be wondering how it all fits together. One thing to remember is that in Java, whenever you have an opening character- {, [, (- you must have a matching closing character- }, ], ). So we see the first line that says public class Hello. As was said, this declares our class. The opening curly brace on the next line signifies the beginning of the class. This means that everything between it and the closing curly brace on the bottom is a part of the class. The curly braces underneath the main() function designate the code that is part of the main() function. I will cover this fully in a later tutorial. But just so ya know...


---------------------------------
Section 4c
More console
---------------------------------
There are two ways to do basic console output. One is to use System.out.println(), and the other is to use System.out.print(). They both have the same syntax, they just operate a tad bit differently. System.out.print() will display the test you pass on a line, but will not create a new line. Thus subsequent calls to System.out.print() will be on the same line. System.out.println() displays text on its own line. Experiment with System.out.print() to see exactly what it does.

There are a few special characters that can be used in stuff you display. They're called escape sequences. A table is below to show you what they are and what they do:

Escape Sequence Description
--------------------------- -----------------
\n Newline. Positions screen cursor at beginning of next line
\t Horizontal tab. Move the screen cursor to the next tab stop
\r Carriage return. Position screen cursor at beginning of current line, don't go to next.
Stuff on this line can be overwritten
\\ Used to print a backslash character
\" Used to print a double quote character.

Here's a quick example: System.out.print("\"This text appears in quotes\" but this doesn't\n");
This will display: "This text appears in quotes" but this doesn't
and move the screen cursor to the next line. This means that all subsequent output occurs on the next line.

-------------------------------
Secion 4d
Graphical output
-------------------------------
This stuff is quite a bit cooler than the console output. To start, let's do a quick program:

// GraphicalOutput.java
import javax.swing.JOptionPane; // Import class JOptionPane

public class GraphicalOutput
{
public static void main(String args[])
{
JOptionPane.showMessageDialog(null, "Hello, world!");
}
}

Compile with javac GraphicalOutput.java and run with java GraphicalOutput.

What you should get is a dialog box that says "Hello, world!" and has a little information symbol on the side. Let's see what's goin on...

import javax.swing.JOptionPane;
This line allows us to include other classes into our programs. It's the same as #include in C/C++. Sun has created a huge library of functions that you can include so you don't have to "reinvent the wheel." This just lets us execute the single command in our program.

The first couple lines are the same.

JOptionPane.showMessageDialog(null, "Hello, world!");
This shows the dialog box. Don't worry about the first argument. Set it to null every time. The second one is obviously the text you want to show in the dialog box.

You can also call JOptionPane.showMessageDialog() with more argument. Here's how:
JOptionPane.showMessageDialog(null, display string, title bar string, message box type);

There are a few message box types: JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, and JOptionPane.PLAIN_MESSAGE.
To display a dialog with the title "I rule" and message "I'm a bad *** programmer" as a warning, use
JOptionPane.showMessageDialog(null, "I'm a bad *** programmer", "I rule", JOptionPane.WARNING_MESSAGE);

This is programming, so experiment with everything.

--------------------------------
Section 5
Basic input
--------------------------------
Oddly enough, input in Java is done far more easily graphically than it is using the console. Anyone working in a shell, get to a GUI for this!

// Addition.java
import javax.swing.JOptionPane;

public class Addition
{
public static void main(String args[])
{
String firstNumber, secondNumber;
int number1, number2, sum;

// Read the first number from user as a string
firstNumber = JOptionPane.showInputDialog("Enter first integer");

// Read the second number
secondNumber = JOptionPane.showInputDialog("Enter second integer");

// Convert numbers from type String to type int
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);

// Add the numbers
sum = number1 + number2;

// Display the results
JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);

System.exit(0); // Terminate the program
}
}


Wow! This is a lot bigger and more complex than our previous programs. It's not that bad, really. Compile and run it to see what it does before reading the explanation. It'll really help.

String firstNumber, secondNumber;
This line declares two variables of type String. As you might guess, these are strings. A variable is a way of storing values. The value in a variable can change at any time, thus the name variable. You declare one by typing type name. Note that variables of the same type may be declared at once, with each variable name separated by a comma.

int number1, number2, number3;
This line declares three values of type int. They're simple integers.

firstNumber = JOptionPane.showInputDialog("Enter the first number");
This line has the user enter something into a dialog box. As was said earlier, methods may return values. The method JOptionPane.showInputDialog() returns a string. This statements calls JOptionPane.showInputDialog(), and stores whatever value it returns nito firstNumber. The method returns a string, which, consequently, is the string that the user enters into the text box.

secondNumber = JOptionPane.showInputDialog("Enter second number");
Does the same as above, but stores the value in secondNumber;

number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
If you want to add two numbers, you have to make sure they're in numerical form. When a number occurs in a string, it is treated as a string, rather than a number. This means you can't add, subtract, or do anything to the number that you want to do with numbers. There's an easy way to get past this. By calling Integer.parseInt() with a string as the argument, you get an int to work with. It does it by searching for a number in the string, and turns it into an integer. The method returns an int, so you have to assign it to a variable, as demonstrated above.

sum = number1 + number2;
If an explanation is necessary, stop reading and go back to first grade.

JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE);
This is just display a dialog box, just like all the others we've done. Note that the second argument, "The sum is " + sum, seems to have two parts. If you have a string you want to display, and want to throw some variables in as well, you can join them with +. Java automatically converts it all to a string, so you don't have to worry about a thing. Pretty sweet...

--------------------------------
Section 6
Wrap up
--------------------------------
Alright, we covered quite a bit here. You learned the basic syntax for Java, did some simple console output, some simple graphical output, and a bit of input. You can convert user's input to integers, and perform any mathematical operation you like on those. I invite you to play around a bit, see what cool stuff you can do, before you head on to the next tutorial.
The next tutorial will cover control structures. This is decision structures and loops. You'll also learn about some of the other data types and how to use them. Happy brewing!

pergesu

#18750 04/05/02 09:20 PM
Joined: Mar 2002
Posts: 562
Le4rner Offline OP
UGN Supporter
OP Offline
UGN Supporter
Joined: Mar 2002
Posts: 562
Java Tutorial - Part II

Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)


Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.


Table of Contents
-------------------------
1) Brief intro
2) Data types
3) Mathematical operators
4) Relational operators
5) Decision structures
a) If
b) If...else
c) else if
d) switch()
e) A final word about decision structures
6) Loops
a) while
b) do...while
c) for
d) A little more on loops
7) Wrap up


--------------------------
Section 1
Brief Intro
---------------------------
Awesome! Welcome to the next part of the series; glad you're here. If you're reading this, I assume you've already read my first tutorial or have some knowledge of Java. In the last tutorial, you learned how to do basic input and output, and using integers that the user input. You're gonna do some more complex stuff in this tutorial. We'll be looking at control structures, which involve decision structures and loops. To use them, you need to know about mathematical operators and relational operators. Read on...

---------------------------
Section 2
Data types
---------------------------
You learned about integers in the last tutorial. They are not the best data type in the world, because they can only represent integers, and are limited in their range. Sometimes we want to use a decimal, and for this, int is inappropriate. Here's a list of the other primitive data types:

char - A single character
float - A floating point value
double - A floating point value; more precise than float
bool - A boolean value. Either true or false (1 or 0)

Each primitive type has a corresponding parse*() method. So for double, it would be Double.parseDouble(userstring). Try them out in a program.

------------------------------
Section 3
Math ops
-------------------------------
. In all the programming you do, you will do an incredible amount of mathematical operations. If you've ever gone to sixth grade, you should get this without any trouble. You just need to know the different operators there are to use. Here's a table:

Operation Operator Expression
-------------- ------------- -----------------
Addition + a + 7
Subtraction - b - 3
Multiplication * c * d
Division / e / f
Modulus % g % h

In case you don't know, modulus yields the remainder of integer division. Thus 16 % 5 is equal to 1. Standard algebraic order of evaluation applies. First parentheses; then multiplication, division, or modulus; then addition and substraction.

You can easily modify the value of a variable, assuming you want to begin with the current value. Let's say you want to add 6 to num1. You could use:
num1 = num1 + 6;
However, a simpler, more compact way is to use:
num1 += 6;
They do the same thing. You can do that with any mathematical operator: +=, -=, *=, /=, %=.

A way to increment or decrement the value of a variable is with the increment and decrement operators.
a++; // Increases value of a by 1
b--; // Decreases value of b by 1

The above increments the variable after you do something with it, called post-incrementing. You can also increment the variable before you do anything with it- pre-incrementing. To make it more clear, here's a code block.

int num1 = 5;
int num2 = 12;

JOptionPane.showMessageDialog(num1++); // Displays 5, but new value of num1 is 6
JOptionPane.showMessageDialog(num1); // Displays 6
JOptionPane.showMessageDialog(--num2); // Decrements num2, so it is now 12. Displays 12
JOptionPane.showMessageDialog(num2); // Displays 12


------------------------------
Section 4
Relational ops
------------------------------
You will often compare different values in your programming. You do this all the time in real life (Which cup has more coke? Which class period is shorter?). Of course you'll need to use it in programming, too. Relational operators are used to compare values. They don't change any values, they simple return true or false based on the condition. You'll understand when we start writing code. Here's a table of the Java relational operators.

Operator Example Meaning
------------- ------------- ------------
== x == y x is equal to y
!= a != b a is not equal to b
> c > d c is greater than d
< e < f e is less than f
>= g >= h g is greater than or equal to h
<= i <= j i is less than or equal to j

--------------------------------
Section 5
Decision structures
---------------------------------
You're gonna learn about decision structures here. Basically, what these do is determine a different path of execution based on certain conditions in the program. You want to one thing for one input value, and a different thing for a different value.

----------------------------------
Section 5a
If
----------------------------------
The simplest decision structure is the if structure. If a certain condition is true, then do something. Here's a quick example:

// If.java
import javax.swing.JOptionPane;

public class If
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;

number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);

if(num1 > num2)
{
JOptionPane.showMessageDialog("num1 > num2");
}

System.exit(0);
}
}

There's really nothing you haven't learned, except for the if test. Let's examine it a bit:
if(num1 > num2)
What this does is test the condition in the parentheses. If the condition is true, then the code inside the next block (delimited by the curly braces) will execute. If not, then nothing happens. Pretty simple. Note that there's no semicolon after the if test. Don't ever put one there, because then the following code will execute no matter what. Also note the curly braces after it. The code in the curly braces is the code you want to execute if the condition is true. If you only have one statement, as we have here, you may ommit the braces. I included them for clarity in this example.


---------------------------------
Section 5b
If...else
---------------------------------
At some point we might want to do something if the condition is false, as well. We could do this:

// IfIf.java
import javax.swing.JOptionPane;

public class IfIf
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;

number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);

if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");

if(num1 < num2)
JOptionPane.showMessageDialog("num1 < num2");

System.exit(0);
}
}

That works just fine, so why do anything else? Well consider this: Each time the program runs through, it checks both conditions. This isn't a problem here, but when we have to test a lot of conditions in larger programs, it becomes quite time consuming! So we have the if...else structure. Check it:

// IfElse.java
import javax.swing.JOptionPane;

public class IfElse
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;

number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);

if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");
else
JOptionPane.showMessageDialog("num1 < num2");

System.exit(0);
}
}

Else works sort of the same as if. If the condition in the if test is false, then the stuff following the else statement gets executed (hey, that sound like an if...else!). The same rules for curly braces apply: You need them for multiple statements, ya don't need em for singles. The thing about the if...else is that if the stuff in the condition is true, then it never looks at the else. There aren't two conditions tested. Keep in mind that an else statement must have a corresponding if statement. If you don't have one, the compiler will choke.


---------------------------------
Section 5c
else if
---------------------------------
That if...else thing is pretty cool. But what about if we want to test a whole bunch of conditions? We could use a number of if statements, but then they'd all be evaulated. We'd like to evaluate only as many as we need. This is where the else if comes in handy. Let's see an example, and then I'll explain it a bit.

// ElseIf.java
import javax.swing.JOptionPane;

public class ElseIf
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;

number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);

if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");
else if(num1 < num2)
JOptionPane.showMessageDialog("num1 < num2");
else
JOptionPane.showMessageDialog("num2 == num1");

System.exit(0);
}
}

Here's what we're doing... We check to see if num1 is greater than num2. If it is, we say so. If not, we check to see if num1 is less than num2. If it is, then we say so. If it's neither of them, then they must be equal, so we say that. The great thing about this is that if num1 is greater than num2, then it just skips all the other stuff and heads straight to System.exit(). Pretty cool, huh? You can put as many else if's together as you like. The else if works almost exactly like the if. Syntax is else if(condition) { code to execute }.


-------------------------------
Section 5d
switch
-------------------------------
It's possible that we want to perform a certain action for a number of specific values of a variable. We could use a bunch of else if statements together. However, it's a bit cleaner to use the switch structure. Here's an example program:

// Switch.java
import javax.swing.JOptionPane;

public class Switch
{
public static void main(String args[])
{
int num;
String number;

number = JOptionPane.showInputDialog("Enter an integer");

num = Integer.parseInt(number);

switch(num)
{
case 1:
JOptionPane.showInputDialog("Number is 1");
break;
case 6:
JOptionPane.showInputDialog("Number is 6");
break;
case 237:
JOptionPane.showInputDialog("Number is 6");
break;
default:
JOptionPane.showInputDialog("Number is somethin else");
break;
}

System.exit(0);
}
}

Wanna know what this does? Well first off, the variable inside the parentheses of switch() is the variable to test. When you run the program, the structure examines the value of num1. It then compares it to the first case you have listed. The cases are meerly possible values for the variable, it's not a list or anything. If the value is equal to the first condition, then it executes the statements up to the break, and then skips everything else in the structure. If the value does not equal any case, then the code under default: is executed. You don't have to have a default:, it's just nice in case the value matches nothing else.
A couple of important things here. Everything dealing with the switch structure is enclosed in a set of curly braces. Also, each case must be ended with a colon. When a case is true, then all the statements up to the next break executed. This means that if you forget a break, then some code may execute that you didn't want. Of course, you can also intentionally do this. Here's an example of a switch statements with piled up cases:

switch(num)
{
case 6:
case 12:
case 18:
JOptionPane.showMessageDialog("Number is divisible by 2 and 3");
break;
}

If the value of num is either 6, 12, or 18, then the message "Number is divisible by 2 and 3" is displayed.

--------------------------------
Section 5e
Final word
--------------------------------
Remember the syntax of all these structures.

if(condition) { code to execute }

if(condition { code to execute }
else { code to execute }

if(condition) { code to execute }
else if(condition) { code to execute }
else { code to execute }

switch(variable)
{
case value1:
code to execute
break;
}


We also have a few logical operators that can be used in conditions. Here's a table:

Operator Meaning Example
------------- ------------ -------------
&& and j == 10 && h > 6
&#0124;&#0124; or j == 10 &#0124;&#0124; h > 6

They have two similar but very distinct uses. The and operator (&&), is true if both conditions are true. The or operator (&#0124;&#0124;) is true if at least one of them is true. Examples:

if(j == 10 && h > 6) // Only executes if j equals 10 AND h is greater than 6
JOptionPane.showMessageDialog("j == 10 && h > 6");

if(j == 10 &#0124;&#0124; h > 6) // Executes if j equals 10 OR h is greater than 6
JOptionPane.showMessageDialog("j == 10 &#0124;&#0124; h > 6");

--------------------------------
Section 6
Loops
--------------------------------
You'll often find that you have to do something over and over. It gets pretty cumbersome typing up the same lines of code to do the same thing. Also, you might not know how many times you want to execute a particular statement or code block. This is where loops come in. Loops can also be called repetition structures.


--------------------------------
Section 6a
while
--------------------------------
This simplest loop is the while loop. Everything in the while loop will execute as long as a certain condition is met. A quick example:

// While.java
public class While
{
public static void main(String args[])
{
int num = 0;

while(num < 10)
{
System.out.print("*");
num++;
}

System.exit(0);
}
}

This sets num to 0, and then goes into the loop. The loop continues until the expression in parentheses is false. Since num is less than 10, the code in the block is executed. I increment num each time so that eventually the expression is false, and control continues onto System.exit(). If you don't change the value of the variable that's tested, then the loop continues forever- probably not what you want. Run the program, and you'll see how it all works. Try getting rid of num++ and see what happens.


--------------------------------
Section 6b
do...while
--------------------------------
The do...while loop comes in handy when we want to loop through a block of code at least once. With the while loop, the code is never executed if the expression is false. The do...while loop guarantees that the loop goes through at least one time.

// DoWhile.java
public class DoWhile
{
public static void main(String args[])
{
int num = 0;
String number;

do
{
number = JOptionPane.showInputDialog("Enter 6");
num = Integer.parseInt(number);
} (while num != 6);

System.exit(0);
}
}

The code in the loop executes at least one time, regardless of the value of num. The user is asked to input 6. If that happens, then the program finishes. If not, the user is asked to input 6 until he does so. Compile and run the program to see what I mean.


Sometimes you want a block of code to execute a number of times, but you don't know when you're writing it how many times it should execute. You want the user to determine it. I guess you could ask the user for the number of iterations (times through the loop) to do, and then set up a while loop to do that. However, that's inconvenient for the user. A much better alternative is to use a sentinel controlled loop. A sentinel is a value that tells the loop it should stop. I'll show you an example. It gets a bunch of numbers from the user, and finds the average.

// Sentinel.java
public class Sentinel
{
public static void main(String args[])
{
int num, sum = 0, counts = 0;
String number;
double average;

do
{
number = JOptionPane.showInputDialog("Enter a number (-1 to stop)");
num = Integer.parseInt(number);
sum += num;
counts++;
} while(num != -1);

average = (double) sum / --counts;
JOptionPane.showMessageDialog("Average is " + average);
}
}

This program will continue getting input from the user until he enters -1. We find the average of all the numbers.
You may be wondering about the line
average = (double) (sum / --counts);

First off, the (double) is called a type cast. We are dividing two integers, yet assigning the value to a double variable. We want to make sure that the double variable has double information, so that there's no data loss. When we use (double), sum and counts are temporarily converted to double so that it works smoothly. After the operation, they're int's again. Also, I decrement counts before it gets used. This is because we don't want the sentinel value counting as an iteration of the loop.


--------------------------------
Section 6c
for
--------------------------------
The for loop is another very useful loop. It creates a loop that iterates a certain number of times. The syntax is shown below:
for(initialize; control expression; step expression) { code to execute }

Note that the different parts of the for loop (initialize, control, and step) are separated by semicolons. Don't put a semicolon after the step expression, though.

It might look confusing at first, but it's pretty simple. Here's a quick demo program:

// For.java
public class For
{
public static void main(String args[])
{
for(int i = 1; i <= 10; i++)
JOptionPane.showInformationMessage("This is iteration " + i);
System.exit(0);
}
}

This loop will execute 10 times, and each time will display what iteration it's on. As with all loops, you put whatever code you want to execute inside some curly braces. In all loops again, if there's only one statement, you may ommit the braces.

Examination of the for loop:
for(int i = 1; i <= 10; i++)

int i = i; This declares the variable i, and sets the value to 1
i <= 10; Keep looping as long as i is less than or equal to 10
i++; Increment i for each iteration of the loop

You can use whatever expressions you want. Here are some examples:
for(int j = 65; j > 3; j--)
for(in bubba = 32; bubba < forrest; bubba += 26)


--------------------------------
Section 6d
A little more
--------------------------------
There are two other things that you can use in any loop you write. They are the break and continue statements.

The break statement breaks out of the current loop, and goes onto the code after the loop. An example:
for(int i = 0; i < 10; i++)
{
if(i == 5)
break;
System.out.println(i);
}

This will print out
0
1
2
3
4

and nothing else

The continue statement skips the rest of the code in the loop and continues with the next iteration. An example:
for(int j = 0; j < 10; j++)
{
if(j == 7)
continue;
System.out.println(j);
}

This will print out
0
1
2
3
4
5
6
8
9

So break breaks out of the loop, and continue continues on to the next iteration. Pretty simple.

-----------------------
Section 7
Wrap up
-----------------------
Cool, so we got control structures done in this tutorial. You now have the ability to write much more complex programs. Go ahead and write a bunch of programs before you move on to the next tutorial. In the next one, I'll be going over methods, which are ways of organizing your programs and promoting reuse. If you've got some spare time, head on over to http://www.promodtecnologies.com to check out some cool stuff. Thanks for reading.

pergesu

#18751 04/05/02 09:21 PM
Joined: Mar 2002
Posts: 562
Le4rner Offline OP
UGN Supporter
OP Offline
UGN Supporter
Joined: Mar 2002
Posts: 562
Java Tutorial - Part III

Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)


Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.


Table of Contents
--------------------------
1) Where we left off last
2) Stuff to check out
3) A first applet
4) Some cool stuff
5) One more applet
6) Final wrap up

----------------------------
Section 1
Where we left off
-----------------------------
If I remember correctly, the last thing we did was loops. You also learned all the different primitive types (int, float, char, double) and how to use them. I said you were going to learn about writing methods in this part of the tutorial, but I changed my mind. Up until now, you've only been writing Java applications. There's nothing wrong with that at all, and in fact, the majority of the programs I write are applications. Some of you, however, may be web designers who want to use Java to extend the functionality of your web page, or you may just want to learn about applets. So in this part, we'll go over applets. I want to write a few applets when we cover methods in the next part.

----------------------------
Section 2
Stuff to check out
-----------------------------
First thing I want you to do is play around with a few applets. Switch on over to your JDK directory, and then go into the demo/applets directory. See what directories are in that, and in each directory is a different applet. Switch into one of the directories, whatever you want. In every directory is a .class file and a .html file. So once you're in one of the directories, type
appletviewer <htmlfile>.html

So if the html file is called tictactoe.html, type
appletviewer tictactoe.html.

----------------------------
Section 3
A first applet
-----------------------------
The first applet we're going to make simply displays a string. Here's the code:

// FirstApplet.java
// Your first java applet
import javax.swing.JApplet; // Import class JApplet
import java.awt.Graphics; // Import class Graphics

public class FirstApplet extends JApplet
{
public void paint(Graphics g)
{
g.drawString("My first applet. Bad *** ...", 25, 25);
}
}

Of course, there is an explanation for all of this. Line by line:

import javax.swing.JApplet;
Works just like the imports that we've used a bit before. What this does is import the JApplet class. Importing this class allows us to create an applet

import java.awt.Graphics;
This class lets us use some graphics functionality of applets.

public class FirstApplet extends JApplet
This is where we declare our class. Most of it is familiar. You may have a question on the "extends JApplet" part. It pretty much does what it says it does. This bit of code means that our class extends the JApplet class. It makes your applet an applet. Without this small inclusion, your code is just a generic application.

public void paint(Graphics g)
This declares a method name paint(). This is almost exactly like the main() method that you've made in other programs. The Graphics g bit is a parameter to the method. Parameters are explained more in a later tutorial. g is an object of the Graphics class. An object is almost the same as a variable, but instead of it being a variable of a primitive data type, it's a variable of a class. I'll go into this in great detail in a later part, but just so you're not too confused... This method is sort of like main(). It gets called automatically when your applet starts up. There are two more methods that start up automatically. Those are for later

g.drawString("My first applet. Bad *** ...", 25, 25);
This line lets you draw a string on the applet. As I said previously, g is an object of the Graphics class. Each object generally has one or more methods that you can call. So what you're doing here is calling the drawString() method from the g object. This is sort of like calling JOptionPane.showMessageDialog(), except that it's being called from the object rather than the class.
The string "My first applet. Bad *** ..." is the text you want to display. the 25, 25 is the coordinates where you want to display it. Coordinate (0, 0) is the top-left corner of the applet. Coordinates are in pixels, so (25, 25) is 25 pixels from the left, and 25 pixels from the top.


You don't run applets the same way you run applications. Compilation is the same, though:
javac FristApplet.java

This gets you a .class file. You need this to include in a .html file. All applets are part of an html file, that's just about all they're good for. So let's create an html file:
<html>
<applet code="FirstApplet.class" width=100 height=50>
</applet>
</html>

If you know HTML, this should be pretty basic. We just have an <applet> tag in the file. In the tag, you have three parts. code="FirstApplet.class" tells the browser what class to check out. Whatever class you have, just put that in the quotation marks. width= and height= are the width and height of the applet, respectively.

After you have your HTML file, you can either open it in your browser or use the applet viewer. Not all browsers supports Java2 yet, so this might not work. I'd go with the appletviewer:
appletviewer firstapplet.html

I called the html file firstapplet.html, but call it whatever you like. This brings up your applet. Pretty cool, huh?

----------------------------
Section 4
Some cool stuff
-----------------------------
This is really quick. In addition to drawString(), there are a few other methods you can use with the g object in your paint() method. You can see them all in the documentation for the JDK. For now, try using the drawLine() method. It... draws a line. Here's the syntax
g.drawLine(beginningX, beginningY, endingX, endingY);

Throw it in a loop, and see what you get. Remember to make at least one of the arguments contain your index:
for(int i = 0; i < 10; i++)
g.drawLine(0, 40, 80, i * 10 + 40);

See what you get.

You can also draw a rectangle:
g.drawRect(topLeftX, topLeftY, bottomRightX, bottomRightY);

I said earlier that paint() gets called automaticall when your applet starts up. There are two more that do this. init() is one, and start() is the other. init() is called before paint() is, and you use it to initialize some of the stuff in your applet. You'll see init() in the next applet. start() will be discussed in a later part.


----------------------------
Section 5
One more applet
-----------------------------
Here's another applet, which shows that you can use any class from the Java SDK in your applets. You're already familiar with some of the methods from the JOptionPane class.

// AdditionApplet.java
import java.awt.Graphics;
import javax.swing.*; // Import package javax.swing

public class AdditionApplet extends JApplet
{
double sum;

public void init()
{
String firstNumber, secondNumber;
double number1, number2;

// Read in the numbers
firstNumber = JOptionPane.showInputDialog("Enter a floating point value");
secondNumber = JOptionPane.showInputDialog("Enter a floating point value");

// Convert numbers from type String to type double
number1 = Double.parseDouble(firstNumber);
number2 = Double.parseDouble(secondNumber);

// Add the numbers
sum = number1 + number2;
}

public void paint(Graphics g)
{
// Draw the results
g.drawRect(15, 20, 270, 20);
g.drawString("The sum is " + sum, 25, 25);
}
}


Everything here you've already done. There may only be two things that sort of confuse you.

import javax.swing.*;
We've always imported a class into the programs. For this applet, we need to import javax.swing.JOptionPane and javax.swing.JApplet. Instead of typing those both, we can just import the javax.swing package. All the classes in the SDK are organized into packages. When we compile this, the compiler looks to see what classes we need from the javax.swing package and includes them. Less typing for us!

double sum;
I'm not sure if I've covered this before. This is a variable that belongs to the class, so it can be used in all the methods of the class. The variables number1 and number2 in the init() method can't be used in the paint() method, but sum can, because it was declared in the class, rather than in a method. I will go over this completely in the next part. I swear.

----------------------------
Section 6
Final wrap up
-----------------------------
In this part, you learned how to make applets. I didn't include too many examples, because you really just needed to learn how to make an applet. I strongly suggest that you make a lot of applets, using all the stuff you've learned so far. The only thing to remember is that you can't use any of the System methods in applets. So now System.out.println(). The next tutorial will cover methods. For sure. Anyway, just write a bunch of applets for now, until the next part comes out. Have fun!
pergesu

#18752 04/05/02 09:21 PM
Joined: Mar 2002
Posts: 562
Le4rner Offline OP
UGN Supporter
OP Offline
UGN Supporter
Joined: Mar 2002
Posts: 562
Java Tutorial - Part IV

Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)

Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.


Table of Contents
--------------------------
1) A check in
2) What are methods?
3) A first method
4) Parameters and arguments
5) How methods work
6) Wrap up

----------------------
Section 1
A check in
----------------------
Last tutorial covered writing simple applets. It didn't show you a whole heck of a lot, but you learned the basic structure of an applet. You already know quite a bit, so you could have plugged some of that in to new applets if you wanted to try your hand at em. If not, that's fine too. In this part, I'm gonna cover methods. We'll just write a few applets and applications in this part. I only want you to get a feel for methods. I'm not gonna describe the programs fully, but I will go over the new stuff, which is just basic methods.


------------------------------
Section 2
What are methods?
------------------------------
Methods are simply ways of breaking up your code to make it more readable, as well as reduce redundancy. This may seem confusing at first, but you'll get it real quick with these examples:

public static void main(String args[])
{
// A few numbers and their squares
int i1, i2, i3, i4, i5, i6;
int square1, square2, square3, square4, square5, square6;

square1 = i1 * i1;
.
.
.
square6 = i6 * i6;
}

public static void main(String args[])
{
// These are the numbers that go into a really long, made-up equation
int a, b, c, d, e;
int f, g, h, i, j;
int k, l, m, n, o;

double result1, result2, result3;

result1 = ((a / 2) + b) / (7 * c) - (6 * d) * e;
result2 = ((f / 2) + g) / (7 * h) - (6 * i) * j;
result3 = ((k / 2) + l) / (7 * m) - (6 * n) * o;
}


These examples don't do much- I didn't want to throw in anything that would confuse you. You'll see that in the first example, you have to write the same thing six times. Wouldn't it be nice if there were a way to not have to type that over and over? The answer is methods. Take a look at the second example. Not only do you have to write the same thing three times, it's much more cumbersome. The equation is lengthy, and you are prone to make errors as you type. Those three statements do the same thing. Why not have some sort of code block that allows you to write one bit of code, then use that a bunch of times in your program? The way to do this is with methods.


-------------------------
Section 3
A first method
--------------------------
I'm sort of lying here... You've written a bunch of methods so far. The main() method in all your applications and the init() and paint() methods in your applets are all methods. However, those methods are all sort of premade, and you never have to call them. In this example, you'll write a really simple application in which you create and call your own method.

// Squares.java
// Finds the squares of integers
import javax.swing.*;

public class Squares
{
public static void main(String args[])
{
JTextArea outputArea = new JTextArea(11, 10); // Don't freak here. I'll explain below
String output = "Number\tSquare";

for(int i = 1; i <= 10; i++)
output += "\n" + i + "\t" + square(i);

outputArea.setText(output);

JOptionPane.showMessageDialog(null, outputArea, "Squares of Numbers",
JOptionPane.SHOW_INFORMATION_MESSAGE);

System.exit(0);
}

public static int square(int num)
{
return num * num;
}
}

Now, for a run-down of the code:

JTextArea outputArea;

outputArea = new JTextArea(11, 10);
This, as you probably guessed, creates an object of a TextArea. An object is just a variable from a class, rather than a primitive data type. As you also probably guessed, we'll use it as an output area. TextAreas have a height and a width. The height is the number of lines in the TextArea. The width... I'm not sure how that's figured. Just experiment with different values till you get one that works. You're probably wondering what the heck new means, and why JTextArea follows it. Up until now, when we've declared a variable, we've just put the type and the name. Objects, however, are generally a bit different. When you declare an object, such as by type JTextArea outputArea, you simply tell the compiler that you have a variable. The computer will not assign it any memory just yet. So for this reason, you have to use the new operator, followed by the class name. What this does is tell the compiler to assign some memory for the object when you run the program. The numbers in the parentheses are arguments to the constructor. Arguments are covered very shortly, and constructors will be covered in a future part of the tutorials. Basically, they are just values to initialize your object. In this case, you're setting the height to 11 lines, and the width to... something long enough to show what we want smile

output += "\n" + i + "\t" + square(i);
Most of this is familiar. The only thing really is the square(i) part. This is just calling the method that you defined after main(). i, which appears in the parentheses, is called the argument to the method.

public static int square(int num)
This is the header for your method. It defines who can see the method, what type of value the method returns, the method's name, and any arguments it takes. In this case, the method can be seen from any program that uses your class (which won't happen with this class), returns an integer, is named square, and takes one argument. This is how you would write the header for any function:

visability return-type name(parameters)

You might wonder why this method is declared static. Well, main() can't call a
non-static method that's not being called on an object or class. So basically, if a
method is not static, main() has to call it this way: object.method() or
class.method(). This actually goes for any static method. You can't call a non-static
method from a static method. This means that you're free to do call non-static
methods in your applets though, as you see below:

public void init()
{ int x = square(5); }
public int square(int num)
{ return num * num }


return num * num;
This just makes the method return the value num * num to the calling method.


----------------------------------
Section 4
Params and args
----------------------------------
Just so you know, what you just read wasn't the final word on the square() function. It tells you what the stuff does, but not how it works. That's the topic of the next section. In this section, though, I want to let you know what parameters and arguments are.
When you write the header of a method, everything that goes inside the parentheses are called parameters. When you call a function, everything that goes inside the parentheses are called arguments. It's really simple.


----------------------------------
Section 5
How methods work
----------------------------------
Cool, so we know how to write a method, and we know how to call and use it. But do we know how it works? I do wink But you will learn really soon. The first thing I want to show you is the return part of a method. Take a look at these method headers:
public void foo(int a)
public int bar(int b)

You already know that the data type that comes before the method name is the return type. This means that at the when the method is done executing, it will return a variable or object to the calling method. The first method is void, so it doesn?t return anything to the calling method. The second method is int, so it returns an integer to the calling method. Here?s a quick code bite:
public double foo()
{
double b = 2.3;
for(int i = 0; i < 60; i++)
b += ((b * i) + 6) / 3;
return 72.6;
}

public void bar()
{
system.out.println(foo());
}

That function really doesn?t do anything for you. It creates a variable, loops 60 times, each time performing some arcane calculation, and then returns 72.6. This means that if you call it from anywhere within your program, it will return 72.6. Every time. Check out the call to the println() method. As a parameter, you see a call to foo(). This may seem strange at first, but it really makes a lot of sense. By making foo() a parameter, you?re telling the println() to print the value that?s returned by the method. So really, any time you call a method, you just get back a value. You can assign this value to variables, just as you would with any other value. So you could do this:
double x = foo();

Now for the slightly trickier stuff. But it?s really not hard at all, I promise. If you don?t know what parameters and arguments are... READ THE PREVIOUS SECTION. When you call a method with arguments, you?re passing some data on to the method, so that it can use it. This enables you to perform the same actions on as many different data as you like. Whenever you call a method, the values of the arguments are substituted for the parameters of the method. It?s really quite simple. Look here:
public void foo(int a)
{
system.out.println(a);
}

public void bar()
{
system.out,println(6);
system.out.println(23);
system.out.println(-87);
}

If you put this code into a program, you will see that it displays 6, 23, and -87 on their own lines. When the first call to foo() is made, the variable a is assigned the value of 6. In the second one, a gets 23, and in the last on, a gets -87. Note that the values are not just substituted in, but that a actually gets the value. This means that you can use a parameter in operations just as you would any variable. You can input into them, assign them different values, etc. One last thing I want you to know is that you can make an argument anything you like, whether it be a value, variable, or expression, AS LONG AS IT?S THE SAME TYPE AS THE PARAMETER. In your method header, the data types of the parameters tell the method what type of data what to expect. If you send data in that isn?t the right type, the compiler chokes. So be careful when calling your methods.


----------------------
Section 6
Wrap up
----------------------
In this tutorial, you learned how to write and call methods. Nothing really fancy, just the basics of methods. Hopefully you can see the benefits of methods. Using them improves readability of your programs, as well as maintainability. You?re able to split up parts of your programs into specialized sections. This ?divide and conquer? strategy is the basis of good software engineering.
In the next tutorial, I?m gonna go over more advanced method stuff. It?s not hard at all, I just want you to be comfortable with methods before hitting the advanced stuff. We?ll go over the differences between passing by value and passing by reference, default parameter values, overloading methods , and recursive methods. Until then, have fun.
pergesu

#18753 04/05/02 09:22 PM
Joined: Mar 2002
Posts: 562
Le4rner Offline OP
UGN Supporter
OP Offline
UGN Supporter
Joined: Mar 2002
Posts: 562
Java Tutorial - Part V

Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)


Feel free to distribute this as much as you like. Just don't modify it at all;
distribute it in its entirety. Check back for more Java tutorials to spread
around as well.


Table of Contents
-------------------------
1) Intro
2) What are arrays?
3) An array program
4) Stuff to know
5) Rand and averaging
6) Passing arrays to methods
7) Why pass by reference
8) Linear search
9) Wrap up

-------------------------
Section 1
Intro
-------------------------
In the last tutorial, you learned how to write and call methods. You basically
just learned the syntax of a method, how do define it, and what the different
parts do. I know I said that we were going to cover more complex methods, but I felt
a change was in order. In this part of the series, you will learn all about arrays
and how to use them.


-------------------------
Section 2
What are arrays?
-------------------------
An array is just a collection of data. The data all have to be the same type.
Furthermore, arrays take up contiguous areas of memory. This last fact isn't
important to you as a programmer, but it is something you should know.
Why should you use arrays? They make your life simple. Suppose you create a program
that gets 10 grades from the user and averages them. You could create 10 variables,
and have the user enter data in that way. I guess if you wrote a function to handle
the input it wouldn't be too bad, but I still wouldn't like typing out 10 function
calls. Just think if you had to do 200 grades! You'd get pretty friggin bored. That's
what arrays are created for. They allow you to group a number of variables into one
variable. You access all the data through one name. It's pretty slick, as you'll see
in the next section. But first, I want you to see how to declare an array:
int intArray[] = new int[5];

The brackets- [] - next to the variable signify that you're creating an array. In
this case, the array is an array of integers, and is called intArray. On the right
hand side of the equals sign you have new int[5]. When declaring an array, you must
use new. new is an operator that assigns memory. In this case, it's saying "allocate
an array of 5 integers and assign it to intArray."

An array has to have a specified number of elements. An element is one part of the
array, it's sort of like a variable. I said earlier that an array is a collection of
data. Each one of these data is called an element. An array may be of any size, as
long as there's enough memory in the computer. You can access an individual element
of the array through index referencing. This is a fancy way of stating which element
you want to play with. You'll see how this all works in the example program. But
enough talk...


--------------------------
Section 3
An array program
---------------------------
// ArrayEx.java
// Shows how to use arrays

public class ArrayEx
{
public static void main(String args[])
{
int array[] = new int[5]; // Creates an integer array of 5 elements

// Access each element individually, and assign it a value
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

// Access each element and print value
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
}
}

If you compile and run this program, you'll get the numbers 1-5. Not anything
special. Now, an explanation of the code

int array[] = new int[5];
This was explained earlier. It creates an array of integers called array with 5
elements. The number in between the brackets on the right hand side is that number of
elements.

array[0] = 1; //and so forth
This shows how you can access an individual element of the array. The first thing I
want you to note is that we treat it just as we would any other integer. That's
because it is! The variable array is a bunch of integers, and each element is just an
integer. So you can do whatever you want with it that you would any integer.
See the number in the brackets? It's called the subscript, and it's the element
you're currently accessing. Array elements range from 0 to arraylength-1. So if you
have an array with 17 elements, the last element in the array is [16]. So array[0] is
the first element, array[1] is the second, and so on.


In that program, we created an array, initialized every element, and displayed the
values of the elements. But see how we had to individually access each element? It
doesn't seem like it saved much time. All it really did was cut back on the number of
variable declarations we made, so it doesn't seem that much of a benefit. But the
beauty is that you can make the subscripts of the array be variables. Hell, you throw
an array in a loop, and it's awesome. Check this out:

// ArrayEx2.java
// Another example of arrays, but with variable subscripts
public class ArrayEx2
{
public static void main(String args[])
{
int array[] = new int[200];

for(int i = 0; i < 200; i++)
array[i] = i * 2;

for(int i = 0; i < 200; i++)
System.out.println(array[i]);

System.exit(0);
}
}

Go ahead, compile and run it. See what it does, then see how it does it...

int array[] = new int[200];
We just created another array of integers. But we made it really big this time, so we
could appreciate arrays. Can you imagine having to type up 200 variable declarations?

First for loop
Here we loop 200 times. Because we're going through the array on each pass, and the
primary intent is to do something with the array, it's commonly called looping
through the array. Here we loop through it, and access each element. We then assign
it a variable value, which is the iteration of the loop times 2. Remember that an
iteration is a pass through the loop. This shows you that you can make the subscript
a variable, not just a fixed value.

Second for loop
We're just looping through the array, printing the values of each element.


----------------------------
Section 4
Stuff to know
-----------------------------
There's a way to assign values to an array right as you declare it. An example is
below:
int a[] = { 3, 4, 9, -7, 16 };

There are some thing to notice. First off, you don't have to have a new in there. In
fact, you can't. By creating the curly brackets and placing values in there, you're
telling the compiler the length of the array. You've also filled the elements with
values. But you still treat it the same way as you would any other array.

This may seem sort of bone headed to some of you, but I just want to make sure that
you all know that you can create an array of any data type. Objects, primitive types,
heck, you can even make an array of arrays. I've just been using integers in the
examples because they're easy to create examples with. Just keep in mind that you can
create an array of whatever you want.

Every array knows it's own length. An array has a property, which believe it or not,
is called length. You can access it using this synxtax:
arrayName.length;
It's quite useful in loops. Very often you'll write a program, and possibly want to
change the number of elements in the array. Instead of hardcoding the loops, you can
just use the array length, and you have to make fewer changes to your code. In all
future examples, I will use the length property of arrays. So don't be freaked when
you see that. You know what it is cause I just told you.


----------------------------
Section 5
Rand and averaging
-----------------------------
This program will be a bit more complex, though nothing over your head. Still
sticking to example stuff. But you're going to learn a few things here. First off,
you'll learn how to generate and use random numbers. You'll also get another chance
at looping through an array, and performing some operations using the data within
the array. So here we go:

// RandAve.java
// Demonstrating random numbers and arrays
public class RandAve
{
public static void main(String args)
{
int array[] = new int[500];
int sum = 0;
double average;

for(int i = 0; i < 500; i++)
array[i] = (int) (Math.random() * 100);

for(int i = 0; i < 500; i++)
sum += array[i];

average = sum / 500;
System.out.println("The sum of the integers is " + sum);
System.out.println("The average of the integers is " + average);
}
}

For an explanation...

int array[] = new int[500];
Create a big array of integers

First for loop
Just fill the array with random numbers

array[i] = (int) (Math.random() * 100);
Here we get a random number between 1 and 100 and assign it to the current element.
Math.random() is a method that lets you get a random number. It actually returns a
floating point value, so to get a number that you want, you have to multiply it by
the maximum possible number. So if you want it to be numbers between 1 and 5, you
would have Math.random() * 5. Note the (int) type-cast in front of it. Remember that
I type cast temporarily changes the data type, so that the compiler can understand
it. Because random() returns a floating point value, you need to cast it to an
integer. That's what this does. If you're wondering how we were able to access the
method without importing anything... Java is pretty cool and automatically imports
some stuff for you. It'll import stuff in the Math package, the System package, and a
couple others. Recall that a package is a group of classes, and they're grouped
primarily by functionality so that you can easily find them.

Second for loop
Gets the sum of all the numbers in the array

average = sum / 500;
Gets the average

Then we display the sum and average of all the numbers in the array.


----------------------------
Section 6
Arrays to methods
-----------------------------
Previously you've learned what a benefit methods can be in your programs. Hopefully
you've also seen how beneficial arrays can be as well. It would make sense that you
should be able to combine both of these benefits to create even more powerful
programs. You already know how to write methods and pass them arguments, so you
really already know how to pass arrays. It's just like passing any other data type.
There are just a few nuances of passing arrays to methods that I want to point out.
The first thing is is that this gets into pass-by-reference, something which I
briefly mentioned earlier. In all the methods that you've written so far (You HAVE
been writing programs on the side, haven't you?), you've passed the variables by
value. This means that whenever you call a method, the value of the variable is
passed, nothing else. You might have noticed that you can modify a variable in your
method all you want, but it remains unchanged outside that method. That's the case
with primitive types, at least.
Pass-by-reference occurs when you pass a method or an object to a method. When this
occurs, the value of the variable is not passed to the method, but rather the address
of the variable. Because the method has access the the address of the variable, any
actions that it takes actually occur on the variable itself, not just a copy. So any
modifications you make to the variable will show up in all other methods. Remember
that this is only with arrays and objects.
There are a number of languages, C and C++ being two, that allow you as the
programmer to determine when variables are passed by reference or by value. In Java,
however, this is not the case. This is the only major limitation I've encountered
with Java so far, and it's something that if you program C or C++, you'll sorely
miss. However, it does reduce errors for the (as yet) unseasoned programmer.
That's a lot of talk, and I know you wanna learn to program, so let's check some
code!

// PBR.java
// Demonstrates pass-by-reference versus pass-by-value
public class PBR
{
public static void main(String args[])
{
int array[] = new int[10];
for(int i = 0; i < array.length; i++)
array[i] = i;

for(int i = 0; i < array.length; i++)
System.out.println("Before any mod, array[" + i + "] = " + array[i]);

for(int i = 0; i < array.length; i++)
modElement(array[i]);

for(int i = 0; i < array.length; i++)
System.out.println("After modElement, array[" + i + "] = " + array[i]);

modArray(array);

for(int i = 0; i < array.length; i++)
System.out.println("After modArray, array[" + i + "] = " + array[i]);

System.exit(0);
}

public static void modElement(int x)
{
x += 3;
System.out.println("Inside modElement, x = " + x);
}

public static void modArray(int array[])
{
for(int i = 0; i < array.length; i++)
{
array[i] += 5;
System.out.println("Inside modArray, array[" + i + "] = " + array[i]);
}
}
}

Compile and run this program, you may be surprised by the output.

The first thing we do is assign values to elements of the array, then display the
contents. Then we pass each element of the array to modElement. Inside this method,
we modify the value of the element, and display it. Then we display the contents of
the array back in the main() method. You will see that the elements are the same as
they were before modElement was called. Next we call modArray(). The entire array is
passed to this method. As I said earlier, arrays are passed by reference, so the
address of the array is going to the method. This means it has direct access to the
contents of the array. The method adds five to each element in the array and then
displays the contents. Then we display the contents back in main(). Notice that the
values are the same. They were changed in modArray, and the changes affected the
array back in main(). But you didn't do anything differently. That's because Java
passes arrays by reference.


----------------------------
Section 7
Why pass by ref?
-----------------------------
If you wondered why Java passes arrays and objects by reference, but primitive types
by value, then you're asking smart questions. Let's think about it sort of closely.
An integer takes up 8 bits, or one byte of memory. So if you pass it to a method, and
it's passed by value, the integer takes up 2 bytes of memory- 1 in the calling
method, and one in the called. Now take an array or an object. An array may have a
large number of elements. In an array of 100 integers, it will take up 200 bytes of
memory if passed by value. This still isn't much, but it gets larger with more
elements. Consider an object. You haven't learned too much about them yet, but they
can contain a large amount of information. A single object could easily take a couple
kilobytes of memory, depending on its size. Passing by value would use quite a bit of
memory. Now if you were to have an array of objects... it could be pretty taxing on
the computer. It's not too much of a problem with today's RAM prices, but copying all
that data still take quite a while, and you lose performance.
As you know, passing by reference just passes the address of the variable to the
method. Because of this, no data has to be copied over. Just think of the performance
gain achieved when a method receives simply 0x2854 (an address in memory) rather than
100 integers. A single hexadecimal value as opposed to a whole bunch of values. It
makes sense.


---------------------------
Section 8
Linear search
---------------------------
One common application of arrays is to contain a bunch of data, and then search
through the data to find a particular entry. There are a number of different
algorithms, and I'll go over the simplest right here. It's something that I'm sure
you could do on your own.

// LinearSearch.java
// A linear search of an array
import javax.swing.*;

public class LinearSearch
{
public static void main(String args[])
{
int a[] = new int[100];
String toSearch;
int num;

for(int i = 0; i < a.length; i++)
a[i] = (int) (Math.random() * 700);

toSearch = JOptionPane.showInputDialog("Enter the value to search for");
num = Integer.parseInt(toSearch);

for(int i = 0; i < a.length; i++)
{
if(a[i] == num)
{
JOptionPane.showMessageDialog(null, num + " was found at a[" + i + "]", "Results",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

JOptionPane.showMessageDialog(null, num + " was not found ");
System.exit(0);
}
}

None of this is really a problem for you. It just creates an array of integers, asks
the user for a number to search for, and then loops through the array checking to see
if the number exists. It does what you want, but it's extremely inefficient. First
off, it just loops straight through. It examines every single element in order, until
it finds what it's looking for. What if it doesn't ever find what it's looking for?
Then it loops through the whole array. It works, but it's not the most efficient
mechanism.


-----------------------
Section 9
Wrap up
-----------------------
This part of the tutorial has gone well over 400 lines, so I think it's probably
time to stop. You covered a lot in this part. You learned how to declare and use
arrays, how to loop through them, getting their length without actually knowing it,
and how the compiler passes different types of variables differently. It's quite a
bit to cover at one time. I left off with saying that the linear search of arrays are
inefficient. I'll cover efficient searching and sorting techniques in a later
tutorial. The next tutorial will most likely go over method overloading. In the mean
time, work on some programs! You already have more than enough knowledge to create
pretty complex programs. Want a big challenge? Why not try to create a really simple
poker program? I guarantee you can do it, you have all the tools, so you just need to
do it. Until next time,
-pergesu


Link Copied to Clipboard
Member Spotlight
Phatal
Phatal
Houston, TX
Posts: 298
Joined: April 2004
Forum Statistics
Forums41
Topics33,840
Posts68,858
Average Daily Posts1
Members2,176
Most Online3,253
Jan 13th, 2020
Latest Postings
Where and how do you torrent?
by danni75 - 03/01/24 05:58 AM
Animation,
by JohanKaariainen - 08/15/19 01:18 AM
Blackbeard.....
by Gremelin - 10/03/18 07:02 PM
my old account still exists!
by Crime - 08/10/18 02:47 PM
Okay WTF?
by HenryMiring - 09/27/17 01:45 AM
The History Thread...
by Gremelin - 08/11/17 12:11 PM
My friend NEEDS your HELP!
by Lena01 - 07/21/17 12:06 AM
I'm having fun with this guy.
by gabithompson730 - 07/20/17 01:50 AM
I want to upgrade my phone
by gabithompson730 - 07/20/17 01:49 AM
Doom 3
by Cyrez - 09/11/14 08:58 PM
Amazon Gift Card Generator/KeyGen?te
by Gecko666 - 08/22/14 09:21 AM
AIM scene 99-03
by lavos - 09/02/13 08:06 AM
Planetside 2
by Crime - 03/04/13 07:10 AM
Beta Testers Wanted
by Crime - 03/04/13 06:55 AM
Hello Everyone
by Gremelin - 02/12/12 06:01 PM
Tracfone ESN Generator
by Zanvin Green - 01/18/12 01:31 PM
Python 3 issue
by Testing - 12/17/11 09:28 PM
tracfone airtime
by Drache86 - 07/30/11 03:37 AM
Backdoors and the Infinite
by ZeroCoolStar - 07/10/11 03:52 AM
HackThisZIne #12 Releaseed!
by Pipat2 - 04/28/11 09:20 PM
gang wars? l33t-wars?
by Gremelin - 04/28/11 05:56 AM
Consolidate Forums
by diggin2deep - 04/21/11 10:02 AM
LAN Hacking Noob
by Gremelin - 03/12/11 12:42 AM
Top Posters
UGN Security 41,392
Gremelin 7,203
§intå× 3,255
SilentRage 1,273
Ice 1,146
pergesu 1,136
Infinite 1,041
jonconley 955
Girlie 908
unreal 860
Top Likes Received
Ghost 2
Cyrez 1
Girlie 1
unreal 1
Crime 1
Powered by UBB.threads™ PHP Forum Software 7.7.5