Scheme->Java Conversion Course 2000

advertisement
Scheme -> Java
Conversion Course 2001
Lab Session 2/2
The Scheme->Java Conversion Course
2000/2001 Webpage has been put up. You can
find the lecture notes, lab notes and lab answers
there.
The link has been set up at
http://www.comp.nus.edu.sg/~ngkittho
Today, we’re going to learn how to write
methods and classes, but first…
let us go over the answer to Lab 1 Qn 1
Classes
• We learnt during the lecture that classes are like
templates/blueprints.
• When you look at a .java file, you will notice that
except for the import statements, the rest of the code is
written in classes.
• During the lecture, it was also mentioned that
classes, being templates, are just lying there, having
no action of their own.
• Since a .java file is made up of “dead” classes, how
does it run? How did your HelloWorld.java work?
Classes - The Method “main”
• In the Java programs you have written so far, you’ve
probably noticed this method :
public static void main(String[] args) throws Exception
• Basically, when you run a class (ie. you type java test ),
Java will look in that for the method main - it is a
reserved keyword in Java
• In a .java file, there can be many classes, but usually,
there will only be one class that will contain the method
“main”…during our cs1102 last sem, we have been
taught the habit of naming that important class main (so
to run it, we type java main )
Classes - The Method “main”
Example of what I mean :
class main
{
public static void main(String[] args) throws Exception
{
//some running code here
}
}
Methods
Hmm…since “main” is a method, why does it have extra
parameters in front of it (public static), instead of the
usual method format :
return-type method-name(arguments) { //body }
The keyword public is an accessibility modifier,
while the keyword static is the static modifier.
Huh??
Accessiblity Modifiers
Remember what I said about .java files usually having
more than 1 class? Well, the accessibility modifiers will
determine how accessible the method will be.
If I define a method to be public, the method can be
called up by other classes. If I define the method to be
private, the method can only be used within the class itself
Think back on your Scheme. When you define a
procedure in the buffer, it can be used by other
procedures in the buffer. But, if inside proc A, we define
another proc B inside…can it be used by other
procedures besides proc A, where it is defined in?
Accessiblity Modifiers
Scheme eg :
(define (procA a b)
(define (procB c d)
…..))
(define (myproc k)
…)
Now…can we call procB from inside myproc?
procB can only be seen and used by procA
In Java, procA and myproc would be considered public
whereas procB is considered private.
Java eg :
Accessiblity Modifiers
class myType
{
public int squareA(int x) { … }
private double logA(int y) {… }
}
/* create a variable based on the class myType */
myType calculator = new myType( );
calculator.squareA(…); //valid statement
calculator.logA(…);
//invalid statement
logA( ) can only be used within class myType, where it’s defined.
A valid example is that of squareA( ) using logA ( ) to help in
some processing of data.
Accessiblity & Static Modifiers
Hope’s that clear enough about the accessibility
modifiers public and private (actually there’s another
modifier protected, but we won’ t cover that - hardly used
in cs1102)
Now, let’s look at the static modifier…
Oh ya, the accessibility and static modifiers can be
applied to variables also, eg : private static int x;
Static Modifier
Usually, when we want to call a method, we have to
create an instance. Eg : when we want to use substring( ),
we need to create a String variable, and then call it by
reference to the String variable.
String s = “Hello!”;
s.substring(2);
You can’t just call by reference to the class, ie. you call
String.substring(2); - it’s not declared static, meaning
that substring( ) is only made available through an
instance of the String class.
Static Modifier
However, there are some static methods in the String
class, for example, the method valueOf( )
This method will take in any primitive data type and
convert it to a String.
So, you can call String.valueOf(true), which will return
you the string “true”. Similarly, String.valueOf(23) will
return you the string “23”
Static Modifier
That’s why the method main( ) is declared static. When
Java runs the code, who’s going to create a variable of
type main (the class) and call the main method?
Basically, when the static modifier is applied to a
variable or method, it becomes available all the time,
right from the beginning of the program runtime.
Regarding methods, if static is not applied, then the
method is only available when you create an instance and
call by that instance.
Static Variable = = Class Variable
When you declare a variable as static, it becomes a class
variable, and is shared by all instances of that class.
Eg :
class example
{
static int bankbalance;
example (int amt)
{ bankbalance = amt; }
//constructor
public int withdraw(int amt)
{ bankbalance = bankbalance - amt;
return bankbalance;
}
}
Static Variable = = Class Variable
Note that the variable bankbalance is static - it will be shared
among all the other instances. For non-static variables, each
instance has its own personal copy - not affected by others
example first = new example(500);
example second = new example(300);
System.out.println(first.bankbalance);
//not 500, but 300
System.out.println(second.bankbalance); //300
System.out.println(first.withdraw(150)); //150
System.out.println(second.withdraw(150)); //0, not 150
All instances of class example share the same static variable
bankbalance.
Sideline : the keyword final
When you declare a variable as final, its value cannot be changed
throughout the whole program. This in Pascal and C is called a
constant.
Eg :
final int x = 5;
x = 6;
//this will give error!
This comes in useful when you want to set up constants - at the
same time implying that you do not want anyone or any part of the
code to “accidentally” change the value.
An example will be the setting up of the constant pi
final double pi = 3.14159265358979323846;
Lab Qn 1
Ok…this lab is to help you practise how to write
methods and classes.
Remember your bank account problem in Scheme? We
are going to do that.
Your .java file will have 2 classes, main and BankAcc
The class main will contain the method main( ) , which
will contain the code to run the whole program
Lab Qn 1
The class BankAcc will contain the account number, the
name of the account holder, and the balance in his
account.
Since you are going to create bank accounts, ie. variables
based on the BankAcc class, you need to define the
constructor for the BankAcc class
The constructor is responsible for initialising the new
object/instance, in this case, initialise the name, account
number and balance to proper values
Lab Qn 1
Besides the constructor (every class has a constructor by
default), your BankAcc class must have 2 other methods a deposit( ) method and a withdraw( ) method. So…your
BankAcc class will look something like this :
class BankAcc
{
//your properties/variables here
BankAcc (int accno, String name, int balance)
{ ….. }
… … deposit ( … ) { … }
… … withdraw ( … ) { … }
} //end class
Lab Qn 1
Ok…first, go into pico, type in the following and save as
lab2in.txt :
99687,Zion,500
W 50
D 100
7123,Cookie,600
W 700
D 100
0001,Speed,350
D 200
W 100
Lab Qn 1
Your program will read in that file as input. It must cater
for a general number of accounts, ie. you shouldn’t
assume that there will always be 3 accounts - the input
file can always change to more accounts.
99687,Zion,500
W 50
D 100
7123,Cookie,600
W 700
D 100
0001,Speed,350
D 200
W 100
Every account is described in 3 lines.
1st line : account-no, name, initial-balance
2nd line : transaction amount
3rd line : transaction amount
For transaction, “W” means withdraw, “D”
mean deposit
Be careful how you tokenize the 1st lines !
Lab Qn 1
In CS1102, you will be often asked to read input
provided by a text file. There is NO need to use
FileInputStreamReader. Just define your BufferedReader
as normal.
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
The only difference is that when you run the class, you
type :
java main < lab2in.txt
When you use stdin.readLine( ), it will then read one line from the
input provided. The text file replaces the user.
Lab Qn 1
Ok…so your program is supposed to read in these info.
Have a loop that will keep reading in this info and
processing it until there is no more input.
String s;
while ( (s=stdin.readLine( )) != null ) //means still have input
{
//your code
}
Lab Qn 1
With every account (3 lines of text), create a new account
based on your BankAcc class, and process the
transactions. After each transaction, you should print out
the account no, name, and balance remaining in that
account
This is what your output should be :
99687 Zion 450
99687 Zion 550
7123 Cookie 600
7123 Cookie 700
1 Speed 550
1 Speed 450
Lab Qn 1
I will post the answers on my webpage. When all the
materials for this course has been revised and checked
thru, I will ask Dr Razvan to email you all the webpage
address…but here it is now, just for your reference :
http://www.comp.nus.edu.sg/~ngkittho
You may download today’s notes from the webpage now
and use it as reference for your programming of this lab
That’s all, folks! You may start now :)
Good luck for your CS1102 next sem,
Schemers 2001!
And thanks to all the Schemers 99 who
have willingly forked out their precious
holiday time to help out for this course
(^ v ^)
/* The End */
Download