| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Jan | ||||||
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | |||
// Rational Class
public class Rational {
private int a; // numerator
private int b; // denominator
// Class Constructor
// creates rational objects without passing any arguments.
// The default Rational number is 0/1. a=0 and b=1
Rational (){
a = 0;
b = 1;
} // end of default constructor
// Constructor with arguments
Rational (int a1, int b1){
a = a1;
if (b1 == 0){
// denominator is zero not acceptable
// create the rational number as a default
// number.
a = 0;
b = 1;
}else{
// denominator is not zero assign b1 to b
b = b1;
}
} // end of constructor with arguments
//Inspectors
//acts on an object and simply return the value for the data members
public int get_a(){
return a;
}
public int get_b(){
return b;
}
// A method whose name is toString takes no arguments,
// returns a String object that represents the content
// of the Rational number. Example: let r=1/2. The method
// returns a string ” 1/2″ that represents the contents of
// the Rational number r.
public String toString(){
return ” ” + get_a()+ “/” +get_b();
}
}
************************************************************************
public class TestRational {
public static void main (String[] args){
// declaration of the rationa objects
// initialization of the Rational Objects
// r1 = 0/1
Rational r1 = new Rational(5,0); // calling the default constructor
// r2 = 0/1
Rational r2 = new Rational(1,2); // calling the default constructor
// r3 = 0/1
Rational r3 = new Rational(2,3); // calling the default constructor
System.out.println(”Rational Number r1 = ” + r1.toString());
System.out.println(”Rational Number r2 = ” + r2.toString());
System.out.println(”Rational Number r3 = ” + r3.toString());
}//end main
}// end TestRational
/*Write a Java program that will read data from the file :
“data.txt” that contains the following:
1
2
3
4
4
5
6
7
8
9
10
and print out their sum. Asssume that “data.txt” cintains integer value only*/
import java.io.*;
class classWork1 {
public static void main(String args[]) {
//we are using 'try' java command to handle exceptions
try {
//create a file writer using the reserved word FileWriter
//The name of the file is passed as a parameter
//the result of this statement is an object:”fw”
//that is used to handle data from the file “output.txt”
FileWriter fw = new FileWriter(”data.txt”);
//write strings to the file
//the method write() is used to write data into the file
//output.txt pointed to by “fw”
for (int i=1; i<11;i++) {
fw.write(i + “\n”);
}
//close file writer
fw.close();
}//end of try
// If a run time error occurs we will display that
//exceptions to the user
catch(Exception e) {
System.out.println(”Exception: ” + e);
}
}//end of main
}//end of class
——————————————————————–
import java.io.*;
class FileReaderData {
public static void main(String args[]) throws IOException{
int sum=0;
char str;
//create a file reader
//The strings will be found in a file called Output
FileReader fr = new FileReader(”data.txt”);
//Read and display characters
int i;
//we using the read method that will help us read data from the file “data.txt”
//the methos will return a -1 if there are no more data to read
while ( (i = fr.read() ) != -1) {
System.out.print( (char) i);
}
sum=sum+(int)i;
System.out.println( “Sum:”+sum);
//close file reader
fr.close();
}
}
Output is:
1
2
3
4
5
6
7
8
9
10
Sum:-1
Press any key to continue . . .
/*Write a Java program that will read data from the file :
“data.txt” that contains the following:
1
2
3
4
4
5
6
7
8
9
10
and print out their sum. Asssume that “data.txt” cintains integer value only*/
import java.io.*;
class classWork1 {
public static void main(String args[]) {
int sum=0;
//we are using 'try' java command to handle exceptions
try {
//create a file writer using the reserved word FileWriter
//The name of the file is passed as a parameter
//the result of this statement is an object:”fw”
//that is used to handle data from the file “output.txt”
FileWriter fw = new FileWriter(”data.txt”);
//write strings to the file
//the method write() is used to write data into the file
//output.txt pointed to by “fw”
for (int i=1; i<11;i++) {
sum=i+sum;
fw.write(i + “\n”);
}
fw.write(”Sum:”+sum + “\n”);
//close file writer
fw.close();
}//end of try
// If a run time error occurs we will display that
//exceptions to the user
catch(Exception e) {
System.out.println(”Exception: ” + e);
}
}//end of main
}//end of class FileWriterDemo
A LINKED LIST is a particular type of
data structure, made up of objects linked together by pointers. In the previous section,
we used a linked list to store an ordered list of Strings, and we implemented insert, delete,
and find operations on that
list. However, we could easily have stored the list of Strings in an array or Vector, instead of in a linked list. We
could still have implemented insert,
delete, and find operations on the list. The
implementations of these operations would have been different, but their
interfaces and logical behavior would still be the same.
The term abstract data type, or ADT, refers to a set of possible values and a set of
operations on those values, without any specification of how the values are to
be represented or how the operations are to be implemented. An “ordered
list of strings” can be defined as an abstract data type. Any sequence of Strings that is arranged in increasing
order is a possible value of this data type. The operations on the data type
include inserting a new string, deleting a string, and finding a string in the
list. There are often several different ways to implement the same abstract
data type. For example, the “ordered list of strings” ADT can be
implemented as a linked list or as an array. A program that only depends on the
abstract definition of the ADT can use either implementation, interchangeably.
In particular, the implementation of the ADT can be changed without affecting
the program as a whole. This can make the program easier to debug and maintain,
so ADT's are an important tool in software engineering.
In this section, we'll look at two common abstract data types, stacks and queues.
Both stacks and queues are often implemented as linked lists, but that is not
the only possible implementation. You should think of the rest of this section
partly as a discussion of stacks and queues and partly as a case study in ADTs.
A stack consists of a sequence of items, which should be thought of piled
one on top of the other like a physical stack of boxes or cafeteria trays. Only
the top item on the stack is accessible at any given time. It can be removed
from the stack with an operation called pop.
An item lower down on the stack can only be removed after all the items on top
of it have been popped off the stack. A new item can be added to the top of the
stack with an operation called push. We can
make a stack of any type of items. If, for example, the items are values of
type int, then the push and pop
operations can be implemented as instance methods
void push (int newItem) -- Add newItem to top of stack.
int pop() -- Remove the top int from the stack and return it.
It is an error to try to pop an item from an empty stack, so it is important
to be able to tell whether a stack is empty. We need another stack operation to
do the test, implemented as an instance method
boolean isEmpty() -- Returns true if the stack is empty
This describes a “stack of ints” as an abstract data type. This
ADT can be implemented in several ways, but however it is implemented, its
behavior must correspond to the abstract mental image of a stack.

In the linked list implementation of a stack, the top of the stack is
actually the node at the head of the list. It is easy to add and remove nodes
at the front of a linked list — much easier than inserting and deleting nodes
in the middle of the list. Here is a class that implements the “stack of
ints” ADT using a linked list. (It uses a static nested class to represent
the nodes of the linked list. See Section 7.6 for
a discussion of nested classes. If the nesting bothers you, you could replace
it with a separate Node class.)
public class StackOfInts {
private static class Node {
// An object of type Node holds one of the
// items in the linked list that represents the stack.
int item;
Node next;
}
private Node top; // Pointer to the Node that is at the top of
// of the stack. If top == null, then the
// stack is empty.
public void push( int N ) {
// Add N to the top of the stack.
Node newTop; // A Node to hold the new item.
newTop = new Node();
newTop.item = N; // Store N in the new Node.
newTop.next = top; // The new Node points to the old top.
top = newTop; // The new item is now on top.
}
public int pop() {
// Remove the top item from the stack, and return it.
// Note that this routine will throw a NullPointerException
// if an attempt is made to pop an item from an empty
// stack. (It would be better style to define a new
// type of Exception to throw in this case.)
int topItem = top.item; // The item that is being popped.
top = top.next; // The previous second item is now on top.
return topItem;
}
public boolean isEmpty() {
// Returns true if the stack is empty. Returns false
// if there are one or more items on the stack.
return (top == null);
}
} // end class StackOfInts
You should make sure that you understand how the push and pop
operations operate on the linked list. Drawing some pictures might help. Note
that the linked list is part of the private
implementation of the StackOfInts
class. A program that uses this class doesn't even need to know that a linked
list is being used.
Now, it's pretty easy to implement a stack as an array instead of as a
linked list. Since the number of items on the stack varies with time, a counter
is needed to keep track of how many spaces in the array are actually in use. If
this counter is called top, then
the items on the stack are stored in positions 0,
1, …, top-1 in the array. The item in position 0 is on the bottom of the stack, and the
item in position top-1 is on the
top of the stack. Pushing an item onto the stack is easy: Put the item in
position top and add 1 to the value of top. If we don't want to put a limit on
the number of items that the stack can hold, we can use the dynamic array
techniques from Section
8.3. Note that the typical picture of the array would show the stack
“upside down”, with the top of the stack at the bottom of the array.
This doesn't matter. The array is just an implementation of the abstract idea
of a stack, and as long as the stack operations work the way they are supposed
to, we are OK. Here is a second implementation of the StackOfInts class, using a dynamic array:
public class StackOfInts {
private int[] items = new int[10]; // Holds the items on the stack.
private int top = 0; // The number of items currently on the stack.
public void push( int N ) {
// Add N to the top of the stack.
if (top == items.length) {
// The array is full, so make a new, larger array and
// copy the current stack items into it.
int[] newArray = new int[ 2*items.length ];
System.arraycopy(items, 0, newArray, 0, items.length);
items = newArray;
}
items[top] = N; // Put N in next available spot.
top++; // Number of items goes up by one.
}
public int pop() {
// Remove the top item from the stack, and return it.
// Note that this routine will throw an
// ArrayIndexOutOfBoundsException if an attempt is
// made to pop an item from an empty stack.
// (It would be better style to define a new
// type of Exception to throw in this case.)
int topItem = items[top - 1] // Top item in the stack.
top--; // Number of items on the stack goes down by one.
return topItem;
}
public boolean isEmpty() {
// Returns true if the stack is empty. Returns false
// if there are one or more items on the stack.
return (top == 0);
}
} // end class StackOfInts
Once again, the implentation of the stack (as an array) is private to the
class. The two versions of the StackOfInts
class can be used interchangeably. If a program uses one version, it should be
possible to substitute the other version without changing the program.
Unfortunately, though, there is one detail in which the classes behave
differently: When an attempt is made to pop an item from an empty stack, the
first version of the class will generate a NullPointerException
while the second will generate an ArrayIndexOutOfBoundsException.
It would be better to define a new EmptyStackException
class and use it in both versions. In fact, the original description of the
“stack of ints” ADT should have specified exactly what happens when
an attempt is made to pop an item from an empty stack. This is just the sort of
small detail that is often left out of interface specifications, causing no end
of problems!
Source: http://math.hws.edu/eck/cs124/javanotes3/c11/s3.html
java.lang.Objectjava.util.AbstractCollection
java.util.AbstractList
java.util.Vector
java.util.Stack
The Stack class represents a last-in-first-out
(LIFO) stack of objects. It extends class Vector with five
operations that allow a vector to be treated as a stack. The usual
push and pop operations are provided, as well as a
method to peek at the top item on the stack, a method to test
for whether the stack is empty, and a method to search
the stack for an item and discover how far it is from the top.
When a stack is first created, it contains no items.
Field Summary |
| Fields inherited from class java.util.Vector |
capacityIncrement, elementCount, elementData |
| Fields inherited from class java.util.AbstractList |
modCount |
Constructor Summary |
|
Stack()
Creates an empty Stack. |
|
Method Summary |
|
boolean |
empty()
Tests if this stack is empty. |
Object |
peek()
Looks at the object at the top of this stack without removing it |
Object |
pop()
Removes the object at the top of this stack and returns that |
Object |
push(Object item)
Pushes an item onto the top of this stack. |
int |
search(Object o)
Returns the 1-based position where an object is on this stack. |
| Methods inherited from class java.util.Vector |
add, add, addAll, addAll, addElement, capacity, clear, clone, contains, containsAll, copyInto, elementAt, elements, ensureCapacity, equals, firstElement, get, hashCode, indexOf, indexOf, insertElementAt, isEmpty, lastElement, lastIndexOf, lastIndexOf, remove, remove, removeAll, removeAllElements, removeElement, removeElementAt, removeRange, retainAll, set, setElementAt, setSize, size, subList, toArray, toArray, toString, trimToSize |
| Methods inherited from class java.util.AbstractList |
iterator, listIterator, listIterator |
| Methods inherited from class java.lang.Object |
finalize, getClass, notify, notifyAll, wait, wait, wait |
| Methods inherited from interface java.util.List |
iterator, listIterator, listIterator |
Constructor Detail |
public Stack()
Method Detail |
public Object push(Object item)
addElement(item)
item - the item to be pushed onto this stack.
item argument.Vector.addElement(java.lang.Object)public Object pop()
EmptyStackException - if this stack is empty.public Object peek()
EmptyStackException - if this stack is empty.public boolean empty()
true if and only if this stack containsfalse otherwise.public int search(Object o)
o - the desired object.
-1source: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Stack.html
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) {
//we are using 'try' java command to handle exceptions
try {
//create a file writer using the reserved word FileWriter
//The name of the file is passed as a parameter
//the result of this statement is an object:”fw”
//that is used to handle data from the file “output.txt”
FileWriter fw = new FileWriter(”output.txt”);
//write strings to the file
//the method write() is used to write data into the file
//output.txt pointed to by “fw”
for (int i=0; i<12;i++) {
fw.write(”Line ” + i + “\n”);
}
//close file writer
fw.close();
}//end of try
// If a run time error occurs we will display that
//exceptions to the user
catch(Exception e) {
System.out.println(”Exception: ” + e);
}
}//end of main
}//end of class FileWriterDemo
___________________________________________
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws IOException{
//create a file reader
//The strings will be found in a file called Output
FileReader fr = new FileReader(”output.txt”);
//Read and display characters
int i;
//we using the read method that will help us read data from the file “output.txt”
//the methos will return a -1 if there are no more data to read
while ( (i = fr.read() ) != -1) {
System.out.print( (char) i);
}
//close file reader
fr.close();
}
}
File streams are perhaps the easiest streams to understand.
The file streams–
FileReader,
FileWriter,
FileInputStream, and
FileOutputStream–each read or write from a file on the native file system.
You can create a file stream from a file name in the form of a string,
a
Fileobject, or a
FileDescriptorobject.
The following
Copy
program usesFileReader
andFileWriterto copy the contents of a file named
farrago.txtinto a file called
outagain.txt:import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File(”farrago.txt”); File outputFile = new File(”outagain.txt”); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }}This program is very simple.
It opens aFileReaderonfarrago.txtand
opens aFileWriteronoutagain.txt.
The program reads characters from
the reader as long as there's more input in the input
file and writes those characters to the writer.
When the input runs out,
the program closes both the reader and the writer.Here is the code that the
Copyprogram uses
to create a file reader:File inputFile = new File("farrago.txt"); FileReader in = new FileReader(inputFile);This code creates a
Fileobject that represents the named
file on the native file system.Fileis a utility class
provided byjava.io. TheCopy
program uses this object only to
construct a file reader on a file.
However, the program could useinputFileto get information, such as its full path name, about the file.After you've run the program, you should find an exact copy of
farrago.txtin a file namedoutagain.txtin
the same directory. Here is the content of the file:So she went into the garden to cut a cabbage-leaf, tomake an apple-pie; and at the same time a greatshe-bear, coming up the street, pops its head into theshop. 'What! no soap?' So he died, and she veryimprudently married the barber; and there werepresent the Picninnies, and the Joblillies, and theGaryalies, and the grand Panjandrum himself, with thelittle round button at top, and they all fell to playingthe game of catch as catch can, till the gun powder ranout at the heels of their boots. Samuel Foote 1720-1777Remember that
FileReaderandFileWriterread
and write 16-bit characters. However, most native file systems are
based on 8-bit bytes. These streams encode the characters as they
operate according to the default character-encoding scheme. You can
find out the default character-encoding by using
System.getProperty("file.encoding"). To specify an
encoding other than the default, you should construct an
OutputStreamWriteron aFileOutputStreamand
specify the encoding. For information about encoding characters, see the
Internationalizationtrail.
For the curious, here is another version of this program,
CopyBytes,
which usesFileInputStreamand
FileOutputStreaminstead ofFileReaderand
FileWriter.source: http://java.sun.com/docs/books/tutorial/essential/io/filestreams.html
You'll be pleased to hear there are NO BITS at all in this lesson! We're
taking a detour via loops, which are useful for repeating things things things
things things things things.
Sorry, that keeps happening, I must have had too many pills again. Anyway,
now you're here, I can tell you there are three types of loops. They all work
in very similar ways, and although they look a bit different, the way they work
is nearly identical. The first type is called a while loop.
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
System.out.println(”Hello, world!”); i++; } System.out.println(”Goodbye!”); } } |
First we'll see what the program does, and then I'll try to explain it.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Goodbye! [nurmes]btg: |
The program prints out the message five times. Try changing i < 5 to i < 3 and it will be printed only
three times.
So what does a while
loop do? Well, as the name suggests, it forms a loop in the program - in other
words it goes back and does the same thing more than once. In this case
“the same thing” is printing a message. Every program we have seen up
to now has run from top to bottom once and that was it. This program repeats
the part which prints the message.
Before I explain exactly how it works, we are going to change the program
slightly:
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
Now it says:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: |
So let me explain. In general terms, a while
loop consists of the keyword while,
followed by some ( )
brackets containing a boolean
expression, followed by a block of statements.
Can you remember what a boolean
expression is? It's what we called a “true or false question”
earlier. It could be as simple as true
or it could be x == 2
(since this is either true or false). It couldn't be x * 2 as this expression will give a
number and not a true or false value. In our example the boolean expression is i < 5.
Can you also remember what a block is? Technically it is zero or more
statements between a pair of curly { }
braces. Each while
statement must have a boolean
expression and a block following it. I'll highlight the block belonging
to our while
statement in blue for you.
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
Now what happens when we reach a while
statement in our program? Well, the boolean
expression is evaluated. Then, if it is true, the code in the block is
executed. Then the expression is evaluated again, and once again if it is true
we execute the code in the block. But as soon as the expression evaluates to
false, we skip over the while
loop and its block, on to the code following it in the program.
So in our example, first the condition (the boolean expression) is evaluated
with i=0 and found to be true. Then the block (also called the body of
the loop) is executed, so we print the current value of i (which is 0) and add one to it.
Next the condition is evaluated with i=1, and so on. The last time through the
loop we print i = 4
and add one to make the new value of i
five. Then the condition is evaluated again, but it is false. So we execute the
last line (saying goodbye).
If all that is too long-winded for you, basically a while loop runs a block of code while
a condition is true. Let's play around with it:
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 0) {
System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
Remember that I just said that the first thing we do here is evaluate the
condition, before running the loop body. The condition will be false
right away, can you work out what will happen?
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Goodbye! [nurmes]btg: |
The body of the loop is never executed, because the condition is evaluated
first of all. You're probably wondering why I pointed that out. Well now we'll
look at a different type of loop, and you should see.
class Hello {
public static void main(String[] args) {
int i = 0; do {
System.out.println(”i = ” + i); i++; } while (i < 5); System.out.println(”Goodbye!”); } } |
This is known as a do…while loop. Notice the semicolon at the end
of the line with the while
on it.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: |
It all seems to be the same so far. There is one crucial difference with
this type, which is that the loop is run once, before the condition is
evaluated. This is why the condition is written at the end instead of the
beginning.
class Hello {
public static void main(String[] args) {
int i = 0; do {
System.out.println(”i = ” + i); i++; } while (i < 0); System.out.println(”Goodbye!”); } } |
So even if the condition is always false, the loop body runs once:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 Goodbye! [nurmes]btg: |
That's the only difference, except don't forget the semicolon after the while. Now for the last type of
loop. You might notice that our very first example had a line to set the loop
counter (int i = 0;)
and a line to add one to it (i++;).
This is very common when you're counting from some number to some other number.
In fact it's so common there is a special type of loop for it:
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
This is called a for loop. Notice that there's only one line inside
the loop body this time, as the i++
has found its way to the top. This is exactly equivalent to the while loop we saw to start with:
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
|
|
class Hello {
public static void main(String[] args) {
int i = 0; while(i < 5) {
System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
Do you like the pretty colours? Let's remind ourselves what these programs
do.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: |
Because any for
loop is equivalent to a while
loop, we can also write a for
loop which never executes the loop body:
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 0; i++) {
System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
|
|
class Hello {
public static void main(String[] args) {
int i = 0; while(i < 0) {
System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
They both do the same thing (we've seen the version with the while loop before).
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Goodbye! [nurmes]btg: |
And that's the three types of loops. Simple, but very useful. Now we're
going to learn about how to break
and continue. These
can be used with any type of loop, but we'll use a for loop to demonstrate. If you can
understand what these two do, and when to use each one, you'll be ready for
anything when it comes to writing your own loopy programs!
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
So we're back with our old friend who says:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: |
Now if we continue
inside a loop, that means to skip the rest of the loop body and carry on to the
i++. The next time
around the loop will behave as normal. Let's try a continue to show what I mean. We'll
be using an if
statement which you should have learned about much earlier.
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
if (i == 2) {
continue; } System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
In this example, we will continue
if i equals two, before
printing the value of i.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 3 i = 4 Goodbye! [nurmes]btg: |
Because the continue
comes before we print the value of i,
the line i = 2
is not printed. So we could use a continue
to skip all odd numbers, for example. Now what about break?
class Hello {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
if (i == 2) {
break; } System.out.println(”i = ” + i); } System.out.println(”Goodbye!”); } } |
A break is rather
more serious - it leaves the loop and doesn't come back. We carry on with the
code after the end of the loop (which just says goodbye).
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 Goodbye! [nurmes]btg: |
Let's try a break
in a while loop.
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
if (i == 2) {
break; } System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
This works just the same as the version with the for loop (try it yourself). Let's
try changing it back to a continue.
This will continue back to the top of the loop (the test part).
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
if (i == 2) {
continue; } System.out.println(”i = ” + i); i++; } System.out.println(”Goodbye!”); } } |
Because the continue
is before the i++,
the value of i will
stay at 2. So we keep going around the loop forever. Before you run the
program, I'll move the printing line to show that this happens:
class Hello {
public static void main(String[] args) {
int i = 0; while (i < 5) {
System.out.println(”i = ” + i); if (i == 2) {
continue; } i++; } System.out.println(”Goodbye!”); } } |
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 2 i = 2 i = 2 i = 2 i = 2 i = 2 ... |
And so on, and so on (you can stop the program by holding the Ctrl key and pressing C). This is a good reason to use a for loop when there is some value
being changed with each run through the loop (like i); when you use continue, the value is still
changed.
When you get around to writing your own programs using loops, it's a good
idea to print out the value of the loop counter (the variable i in this case) each time, like I
have. This makes it easier to see what is happening. Anyway, let's get on to
another couple of examples:
class Hello {
public static void main(String[] args) {
while (true) {
System.out.println(”Hello!”); } } } |
Use while (true)
whenever you want to repeat something indefinitely. For example: reading
commands from the computer keyboard until you get a QUIT command. When you get
the QUIT command, use a break
to get out of the loop.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Hello! Hello! Hello! Hello! Hello! Hello! Hello! ... |
Just to convince you that for
loops can be used for something besides counting 0, 1, 2, 3, here's another
example:
class Hello {
public static void main(String[] args) {
for(int i = 34; i >= 17; i -= 2) {
System.out.println(”i = ” + i); } } } |
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 34 i = 32 i = 30 i = 28 i = 26 i = 24 i = 22 i = 20 i = 18 |
Here we are counting down in twos from 34. Remember that i -= 2 means “subtract
two from the value of i and store it back in i”.
That's enough for a while! Geddit? Well anyway this is
the end of the lesson, please fill
Source:
http://www.javaforstudents.co.uk/loopy.html
Named constant
Some data must not be changed. For example the pay rate might be the same for all part-time employees. The value in a conversion formula that converts inches into centimeters is fixed because 1 inch is always equal to 2.54 cm. When stored in memory, this type of data must be protected from accidental changes during program execution. In Java you can use a named constant to instruct a program to mark those memory locations in which data is fixed throughout program execution. A named constant is a memory location whose content is not allowed to change during the program execution and to declare it you use the following statement:
static final dataType IDENTIFIER = value;
static may or may not appear when a constant is declared
final double CONVERSION = 2.54;
final double PAY_RATE = 15.75;
What all of this mean? First it tells the compiler to allocate enough memory to store a value of type double and to call this memory space CONVERSION and store the value 2.54.
Variables
Obviously certain data must be modified during program execution and this type of data must be stored in memory cells whose contents can be modified during program execution, they are called variables. The syntax will be the following:
dataType identifier1, identifier2, …;
double amountDue;
int counter;
What all this means? First it tells the compiler to allocate enough memory to store a value of type double and call it amountDue. Variable means a variable memory location. And to assign a value here it is :
variable = expression;