|
Site Index
About Me
Welcome
Definition of Program
Variable Types
Understanding Memory
Declaring Variables
Simple Commands
Concatenation and Strings
Sleep-Threads-Try
Catch
Campus Scenes
Pictures
Java simplified
Application Shell Styles
Reading Data From
File
Overview of Applets
Excellent Graphics
Applet
Online Reference
Nested
if statements
Arrays
Sorting Arrays
Using Strings
Functions
Top
20 Replies
First program 211
Important Class Example
JAVA in SDK Environment
Understanding
OOP
OOP simple example
Recursion example
Example of Inheritance
and use of JTextArea
*** Web Related **********
Build Student Web Page
?
What
is FTP
Download
WS ftp95
Download
Java Plug In
Applets
from jbuilder to sdk
Practice Problems

Programming Examples
| |
| Programming Fundamentals Step by Step Guide
To Learn How To Program
- Different programming languages each have their own
syntax and appearance, but my concern here is to acquaint you with the
basic nature of programs and how to write and understand them. These concepts are pretty much the same in all languages. (C++, Java
etc.)
- In my illustrations below, I will follow the Java
syntax
- Make up variable names to hold values in the program
- Use Variable names that are easy to identify
- These variables will take on values when the program
executes -- plan ahead
so you can create variables that you will need to make the program
function.
This is a hard task because you need to be able to envision the
program executing.
You have to write the commands or steps for this execution. Different
tools such as flowcharts can help in this task but basically you have
to be able to see the solution to the problem and write the steps to
make it happen. -- HARDEST THING FOR STUDENTS TO LEARN.
- Beginning programmers will normally be told WHAT THE
PROGRAM IS EXPECTED TO PRODUCE and WHAT THINGS OR DATA THE PROGRAM HAS
TO WORK WITH.
- In essence, program will process data and produce
output results. Keep this in mind
as you review all the code that follows.
- I will use // for comments in all the code examples
that follow Comments are for documentation purposes only and do not
affect a program's execution.
- The programmer then starts to create variables and
uses the commands for the specific language to solve the problem.
- Data that is to be processed is normally put into variables in one of two ways:
...
ASSIGNED
denoted by an = sign.
... INPUTTED from the keyboard or from a file
- Remember that a variable can hold only one thing at a
time for example someone's age, weight, name, address etc.
- We have different types of variables based upon the
type of data that they can hold.
- Common types are integer, float, Char, String,
Boolean.
- Integers hold whole numbers
Floats hold numbers involving decimal points
Char holds one character like 'M' or 'F'
Strings hold groups of characters like people's names
Boolean holds true or false state not "true" but value
true.
- The actual commands in a programming language are
simple to understand
and there are not very many of them
- Command in a language can t\really be broken down
into 4 types
Commands for assigning data to variables
commands for inputting data into variables
Commands for outputting the data that is in variables
Commands for controlling the order of processing the above three
Command types
- In short, the actual commands in a programming
language are easy to understand.
It is truly understanding the concept of variables and how to use
them, that is difficult for the beginning programmer.
- Students must accept the fact that the computer only
does one thing at a time.
It just does it extremely fast. (Like millions of commands in a split
second)
- You must know how to solve a problem in your mind or
you cannot program the computer to do it for you.
- You must learn to break down the solution to a
problem that exists in your mind
into small steps because remember the computer only does one thing at
a time.
- A good example is as follows:
Look at 3 number and tell me the largest. Anyone can do this if you
ask them to.
But in writing a program to do this, you must be able to breakdown the
little steps that your mind went through in solving the problem. You
might say I just looked at the 3 numbers and spotted the largest and
the rest is history. To program the computer to solve this
problem, you must be a whole lot more specific and detailed.
FOR EXAMPLE:
... which number did you look at first
,,, is the first one looked at automatically the highest to start
... how is your mind comparing the numbers
... how do you know when to quit
... etc.
- Remember that understanding variables are the key to
programming and DO NOT FORGET that a variables can only hold one value
at a time. That does not mean that a variable cannot be reused or
added to etc. It just means that at any instant in time
a variable will only have one specific value in it.
- Remember that beginning programmers will normally be
told what is their input for the program and what is expected as
output.
- In the above problem, a teacher might say:
INPUT the 3 number one at a time, and find the largest or
he might say ASSIGN the 3 number to 3 different variables and go from
there
to find the largest.
- You can see from this that a programmer must be aware
of how the 3 numbers are going to get into the program for processing.
- Next the programmer needs to know how to compare
things (to find the largest)
The program does not just look and it knows (like we think our mind
does because
we have done such a task millions of times)
- An "if" statement is used by the programmer
to compare things. It is really the same as the one that our mind uses
in comparing things.
- The "if" statement is an important control
statement in all programming languages.
- The "if" statement is what allows programs
to make decisions and in the above example aren't we trying to decide
which number is the largest.
- To reiterate some important points:
Data is assigned or input into variables
Programs can compare the data that is in variables , knowing that a
variable can only hold one value at a time, by using "if"
statements.
- One more important point to note here: Programs
refer to variables in all their
commands. But remember that it is the data that is in the variable
that is actually being referred to. Put another way, variables are
symbolic names for data that has been put into the variable.
- Some schools of thought will teach students to write
programs by organizing their logic using different approaches --
flowcharting or breaking the program down into smaller pieces.
These approaches are right but I am taking this to a simpler level.
We will analyze variables and commands to a point that we totally
understand them -- then we can talk about organizing our logic according
to a more sophisticated scheme.
- Variables are what the program actually manipulates
or plays with.
- Variables will always be created with an exact purpose
in mind.
- If you do not know why you are creating a variable
then you probably do not need it or you do not know the real nature of
the problem or how to solve it.
- Some variables will be reused by the programmer. They
will take on a value by
assignment or inputting and after the commands have dealt with
the variable (its value), THE VARIABLE CAN BE REUSED. Variables used
for this purpose are normally associated with inputting data (from
keyboard or file) into our program.
- Other variables will take on values (usually by
assignment) and these variables
will not be reused because these values are to be maintained until the
program has completed execution. Counters are good examples of these
types.
- Remember that when declaring or creating variables,
use names easy to identify and make sure that the TYPE of variable
your choose is appropriate for the values or data that it will
contain.
- I need to explain the following 5 commands before we
can start writing programs:
... assignment statement
... input statements and output statements
... if statements
... do while statements
- Assignment statements are use whenever you want to
put a value directly into a variable. SYNTAX
is variable = expression;
Only one variable on the left of = sign. The = sign means "is
assigned the value of".
On the right of the = sign, you can have variables, constants, or a
combination of these separated by arithmetic operators.
e.g.. count =
0;
// used for comments initialize count to 0
total = num1 + num2;
avg = (n1+n2+n3+n4)/4;
counter = counter
+1;
// add 1 to counter
- In the above notice how commands end in a semi colon
and notice how comments are used to help describe the actions
- I recommend that you declare all your variables at
the top of the program, prior to|
their usage. In that case the variable declarations listed below would
precede the commands demonstrated in step 41 above.
// declare all your variables at top of program
int count;
float n1,n2.n3.n4,avg;
int num1,num2,total;
int counter;
- By the way variable names are made up of letters,
numbers, and underscore character. Capital and small letters are
allowed.
EXAMPLES
bb
// okay but too short for identification purposes
male_counter
// good name
counter_for_males_whoi_are_heavy // okay but
too much typing
- INPUT and OUTPUT statements can take many forms in
java but for simplicity
I will use the
System.out.print
// to print results to the screen
System.out.println // print
results to screen and
advance to the next line
File.read...
// to input data or values from a file
the ... will be
substituted by Int, Char, Float, UTF(string data)
- Remember that when you are inputting data you
normally input logical units
not isolated characters or numbers. For example MARY not M and A and R
and Y
or 212 as someone's weight not 2 and 1 and 2. I think you see my
point.
- When inputting more than one thing in the input
stream, a space normally is used to separate the logical units noted
above.
- The actual use of the 2 commands noted above for
input and output will become obvious in the examples that follow.
- IF statements are used for decision making within the
program.
A simple if statement takes the following form
if ( condition)
{
// any statements that you want to do if the condition is true
}
else
{
// any statements that you want to do if the condition is false
}
- In the above example
1... the else is optional
2... the brackets can be deleted if you only want to do one
statement
in the block
3... the condition is any valid expression or comparison that
can be
evaluated to true or false
- Condition normally involve relational symbols like
> < == != etc. which stand for less than
greater than equal to not equal
to. I think you imagine what some other might be.
- Last I will describe the do while command
sequence
do
{
// in English -- perform the statements in the brackets
// as long as the condition is true
}
while(condition);
- All java programs have a weird set of statements
called a shell. I will not deal with them because that will only
confuse the issue. They are required and most advanced
programmers know their purpose. .
Understand all the examples that follow and you are
on the way to programming
In order to show many examples and not confuse students with the
inputting of values from the keyboard or from a file, I will not get into
some of the technical issues concerning input of data. In all my
examples I will use a
file.read...
command. Depending on the type of data being read, I will substitute
a Chr, Int, Float, UTF ( for strings data ) in place of the ... Therefore we can concentrate on
logic development and not dwell on one slightly technical issue.
| 1 |
// assign a value to num1 and num2 and compute
the total
int
num1,num2,total;
// declare 3 integer variables
num1=10;
num2=33;
total = num1 +
num2; // get
the sum into total
System.exit(0); |
| 2 |
// input an integer and print it 3 times
int number;
file.readInt(number);
System.out.print(number); //
print the data 3 times on same line
System.out.print(number);
System.out.print(number);
System.exit(0); |
| 3 |
| // input an integer and print 3 times on separate
lines using loop
int number,counter;
// declare variables
counter=0;
// initialize loop counter
number=file.readInt();
// input aan integer number
do
{
System.out.println(number);
// print the number and go to next line
counter = counter +
1;
// increment counter
}
while(counter < 3);
System.exit(0);
|
| 4 simple if and else but
only one command in each branch |
| // input 2 integer numbers and print the largest
int number1,number2;
number1=file.readInt();
number2=file.readInt();
if(number1 > number2)
System.out.print(number1);
else
System.out.print(number2);
Sysatem.exit(0);
|
| 5 simple if with no else |
| // input 2 integer numbers and print "hello"
only if first number beats second
int number1,number2;
number1=file.readInt();
number2=file.readInt();
if(number1 > number2)
System.out.println("hello");
System.exit(0);
|
| 6 reading a string |
// input a person's name, then their age and print the
name one time
// for each year in their age
String name;
int age,count;
count=0;
name=file.readUTF();
// how strings are read like people's names
age=file.readInt();
do
{
System.out.println(name);
count=count+1;
}
while(count<age);
System.exit(0);
|
| 7 concatenation |
// inpu someone's age and tell how many tines a 5 wil
divide evenly the age
Int age,number _of_times;
number_of_times=0;
age=file.readInt();
if(age>=5)
{
do
{
age=age-5;
number_of_times=number_of_times+1;
}
while(age>=5);
}
// example of printing a heading along with a result in output to
screen
// also demonstrates concatenation
sticking things together using +
System.out.println("number 5 went into age variable " +
number_of_times);
System.exit(0); |
| 8 truncation involving
integers |
// same program as #7 but demonstrates
truncation which occurs when
// two integers are divided (all fractions are dropped)
Int age,number _of_times;
number_of_times=0;
age=file.readInt();
number_of_times = age / 5;
System.out.println("number 5 went into age variable " +
number_of_times);
System.exit(0); |
| 9 ++ shortcut operator |
| // print the number 1 thru 20 on separate lines in
output
int num=1;
// declaring aan int variable and initializing at same time
do
{
Syste.out.println("number is
"+num);
num
++;
// another way of adding 1 to a variable
}
while ( num <= 20);
System.exit(0);
|
| 10
if with multiple items in true branch |
// print number 1 thru 100 such that only 10 values
will appear on each
// output line
int num=1;
int line_count=0;
do
{
Syste.out.print(num+" ");
num
++;
// another way of adding 1 to a variable
line_count ++;
if(line_count = 10)
{
Syste.out.println();
line_count = 0;
}
}
while ( num <= 100);
System.exit(0);
|
| 11 nested if
statements |
| // input 3 integer numbers and print only the largest
int number1,number2,number3;
number1=file.readInt();
number2=file.readInt();
number3=file.readInt();
if(number1 > number2)
{
if(number1 > number3)
System.out.println("largest one is "+number1);
else
System.out.println("largest one is "+number3);
}
else
{
if(number2 > number3)
System.out.println("largest one is "+number2;
else
System.out.println("largest one is "+number3;
}
System.exit(0);
|
| 12 |
// student took 4 courses enter hours credit and
letter grade
// and comput his/her grade point average
int count=0;
char letter;
int hours;
float gpa;
float tot_hours=0;
float tot_quality_points=0;
do
{
letter=file.readChar();
hours=file.readInt();
if(letter == 'A') tot_quality_points=tot_quality_points
+( 4 * hours);
if(letter == 'B') tot_quality_points=tot_quality_points
+( 3 * hours);
if(letter == 'C') tot_quality_points=tot_quality_points
+( 2 * hours);
if(letter == 'D') tot_quality_points=tot_quality_points
+( 1 * hours);
if(letter == 'F') tot_quality_points=tot_quality_points
+( 0 * hours);
tot_hours = tot_hours + hours;
count ++;
} while ( count < 4);
gpa = tot_quality_points / tot_hours;
System.out.println("gpa for this student is
"+gpa)'
System.exit(0); |
| 13 use of %
(remainder) and continue (stay in loop but skip to
the while |
// add up the numbers between 1 and 1000 but skip and
number that
// is evenly divisable by 7
int count=0;
int total=0;
int rem;
do
{
count ++;
rem = count % 7; // perform
division but assign remainder to 'rem'
if (rem == 0)
continue;
else
total =
total + count;
} while (count < 1000);
System.out.println("the total is "+total);
System.exit(0); |
SLIGHTLY MORE
ADVANCED...
ARRAYS and using FOR LOOPS |
Arrays are simply multiple
storage locations under one Variable name !! All the rules
concerning variables apply to arrays. The only
thing different is that we must indicate which element in the array
that we are referring to when a specific Java command is executed.
Specific elements or locations are referred to by means of a
subscript. One dimensional arrays will have 1 subscript and two
dimensional arrays will have 2 subscripts. The following examples
will demonstrate the use of arrays and how to refer to the various
elements. FOR loops are similar to 'do
while' loops as noted in many of the examples above. They
however provide for simplicity
because in one command they specify
1... starting value of a variable
2... test condition for doing the loop
3... what to do to the variable each time
thru the loop |
| |
| 14 simple one dimensional
array example -- also using 'fof' loop structure |
// declare 1 dimensional integer array, input 10
numbers into the array, and
// print them out in the opposit order as they were read in (as data)
int num[] = new
int[10]; // declare 1
dimensional integer array with
// 10 locations.. automatically numbered 0 thru 9
int cnt;
for ( a = 0 ; a <= 9 ; a = a + 1 )
{
num[a] = file.readInt();
// read values into the array
}
for ( a = 9 ; a >= 0 ; a = a - 1 )
{
System.out.println( num[a]
); // print values in the array starting
with last
}
System.exit(0);
|
| 15 |
// declare an integer array (one dimensional) and
assign the number 1000 thru 10000 to locations 0 thru 9
int num[] = new int[10];
int count = 1000;
int a;
for ( a=0;a<10;a++)
{
num[a] = count;
cpount = count + 1000;
} |
| 16 |
// double each value in the array declared in #15
(above)
// and then concatenate all 10 values to a string called out
// such that when printed, each value and its position in the array
// will be printed on separate lines
String out=" ";
for (a=0;a<10;a++)
num[a]=num[a] *
2;
// no brackets needed when only 1 statement
for (a=0;a<10;a++)
out = out + a + num[a] + "/n" );
System.out.println(out);
system.exit(0); |
| 17 |
// declare a 2 dimensional array called num that is
integer and has
// 10 rows and 10 columns. Then put the number 1 thru 100 into the
array
// row wise (going accross)
int num[][] = new int[10][10];
int a,b,count;
count = 1;
for (a=0;
a<10;a++) // a is
used as the row pointer
{
for
(b=0;b<10;b++) // b is used as column
pointer
{
// b is the inner loop so it varies quicker
num[a][b] =
count;
count = count
+1;
}
} |
| 18 |
// given the task accomplished in #17 (above)
// add the respective values found in row 0 thru 2 to the respectine
values
// found in row 7 thru 9
for (a=0;a<=2;a++)
{
for (b=0;b<=9;b++)
num[a+7][b] =
num[a+7][b] +
num[a][b];
}
|
| 19 sort |
// sort a one dimensional integer array (100elements)
high to low
// assume the array already contains data -- array name is num
int a,b,c;
for (a=0; a<=98; a=a+1)
{
for (b=a+1; b<=99; b=b+1)
{
if ( num[a] < num[b] )
{
c=num[a];
3 statements to swap values
num[a] = num[b};
num[b] = c;
}
}
} |
| 20 |
// a cool way to merely assign values to a 2
dimensional float array
the array dimension are set implicitly by the assignment
// assognment takes place row wise (accross columns)
// The code below places 15 values into an array that is implicitly
// declared as having 3 rows and 5 columns
float avg[][]={
{1.5, 2.3,
2.1,9.2,3.3},
{2.4,7.9,11.2,9.3,1,7},
{4.3,4.9,2.8,1.2,33.4) } ; |
| 21 |
// add the total of the odd numbered elements in an
int one dimensional
// array to each even numbered position ... Assume the array already
// contains values
int n[] = new int [100];
int a,b,t=0;
for(a =1;a<100;a+=2)
t = t + n{a];
for (b=0;b<100;b=b+2)
n[b] +=
t; // shortcut
for n[b] = n[b] + t; |
|
Organizing Your Logic
Into An Executable Program
...3 Different Approaches...
1....Put all your variables and
instructions, one after another, and have them execute
2....Organize your logic into smaller
pieces called Functions, whereas each Function will perform specific
tasks ... more organized approach than number 1
3....Use true Object oriented design
where you will create classes which contain their own instance
variables and methods (or functions) that allow use and access to
the variables
|
| Before discussing the 3 approaches it is important to
understand one more thing. All JAVA programs have a series of IMPORT
statements above the program. These statements basically allow
the program to have access to different features and capabilities
that are inherent in the JAVA language. To keep it simple, think of
these statements as allowing your program to use things (code
already written) that will perform a task for you. Saves you
having to reinvent the wheel every time you write a program. In the
examples below, I will use the word IMPORT at the top of a program
to signify this feature. I will not get into specifics as to what
different things we are importing. (This is more technical and does
not need to be dealt with at this point). As you start to write more
sophisticated programs in JAVA, you will see the importance of IMPORTS
because you will want to do something special and you will
realize that the feature is available for you if you import a
package that will allow you to use the feature. |
| APPROACH 1 |
import ......
public class Application1
{
public static void main(String args[])
{
DECLARE ALL VARIABLES
WRITE ALL JAVA COMMANDS
System.exit(0);
}
} |
| APPROACH 2 |
import....
public class Application1
{
public static void main(String args[])
{
DECLARE VARIABLES
function1();
// call function1
function2(); // call
function2
System.exit(0);
}
// end main method
public static void function1 ()
{
// code to perform
operations
}
public static void function2 ()
{
// code to perform other
operations
}
} // end class
|
| APPROACH 3 |
import .....
public class Application1
{
public static void main(String args[])
{
Budget app = new Budget(); //
create object of Budget class
app.EnterName();
app.EnterAge();
System.exit(0);
}
}
public class Budget
{
private String Name; //
instance variable
public
Budget()
// class constructor
{
......
}
public void EnterName() // method available in
the class
{
.....
}
public void EnterAge() // another method in
the class
{
.....
}
}
// end of class
|
| 26 |
| |
| 27 |
| |
| 28 |
| |
| 29 |
| |
| 30 |
| |
| |
| |
|
|