Download Lab Session 1 Notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Scheme -> Java
Conversion Course 2001
Lab Session 1/2
Time to face the Java monster!
Ok, first, we need to telnet.
Only the sun servers support Java,
ie. sun450, sununx, sunjava, sunfire
and sundb
decunx does not support Java
If you have Java installed on your laptop or
computer, you need not telnet to SoC…
We will teach you where to get the Java
programming language afterwards
Once in, run pico - this will be
where you will type out your Java
code when in a telnet session…do
not use Emacs as it is resourcehungry and will take a longer time
to load especially given the huge
amount of students taking cs1102
with you :)
Save all your files with the
extension .java
Eg : test.java
To compile :
javac test.java
You will then see some .class files
being generated
To run :
java classname
Ok…first, type this in and save as
HelloWorld.java :
import java.io.*;
class HelloWorld
{
public static void main (String[ ] args) throws Exception
{
System.out.println(“Hello World!”);
}
}
After saving, exit pico and type at the prompt :
javac HelloWorld.java
You will see a HelloWorld.class being generated.
To run, type :
java HelloWorld
You should see the screen display :
Hello World!
Any problems? Check through your code
again…remember Java is SUPER casesensitive! helloWorld HelloWorld!
Any problems, raise your hands - your friendly
seniors standing by :)
Ok…now, go into pico, type this and
save as testprint.java :
import java.io.*;
class main
{
public static void main (String[ ] args) throws Exception
{
System.out.print(“1st ”+ “ line”);
System.out.println(“ Huh?? How come same line?”);
System.out.print(“\t How did this move out so far?”);
System.out.print(“\n I thought print( ) prints on same line?”);
}
}
Follow the steps previously used to run
HelloWorld.java
??? How come I don’t see a testprint.class ??
Ans - That’s becos when Java compiles a .java file, it
generates .class files based on what classes there are inside
So, you should see a main.class instead…by right, it’s
easier if you name the .java file after the class inside, but
these come in :
• There’s more than 1 class inside
• Your assignment requires you to name it otherwise
(eg. cs1102 assignment)
To run, type :
java main
Observe what is being displayed on the screen.
The method println( ) is designed with special features, known as
escape sequences :
Escape
Sequence
Type
Escape
Sequence
Character
Represented
Special
\b
\t
\n
\f
\r
\”
\’
\\
Backspace
Horizontal tab
Linefeed
Form feed
Carriage return
Double quotation mark (“)
Single quotation mark (‘)
Backslash
Escape
Sequence
Type
Escape
Sequence
Character
Represented
Octal
\DDD
Character with ASCII code DDD
octal, where DDD is a sequence of
three octal digits (0-7), eg. \071 is
ASCII char 71 octal, 57 decimal
Unicode
\uHHHH
Character with Unicode value HHHH
hex, where HHHH is a sequence of
four hexadecimal digits (0-9, A-F),
eg. \u0041 is Unicode char 41 hex,
65 decimal
Strings
• Strings are sequences of characters.
• In Scheme, you have
'(a b c d e)
• In Java, strings are declared with the String
constructor.
String name = ”Scheme";
Strings – Properties
• Strings are actually an array of characters.
String s = "I am a Schemer!";
index
0
I
1
2
3
a
m
4
5
a
6
7
8
9
10
11
12
13
14
S
c
h
e
m
e
r
!
What is the length of this string?
15
Strings – Extracting Characters
0
I
1
2
3
a
m
4
5
6
a
7
8
9
10
11
12
13
14
S
c
h
e
m
e
r
!
String s = "I am a Schemer!";
int len = s.length();
char m = s.charAt(8);
System.out.println(s.indexOf("Scheme"));
System.out.println(s.substring(7));
System.out.println(s.substring(7,13));
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
//
//
//
//
//
7
Schemer!
Scheme
i am a schemer!
I AM A SCHEMER!
Strings – Comparing Strings
• Many times, you might need to compare 2
strings to see if they match.
String s1 = "hello", s2 = "hallo";
or use compareTo
if (s1.equals(s2)) {
System.out.println("Equal!");
}
else {
System.out.println("Not Equal!");
}
String Tokenizer
• Let’s look back at our first example of a
string.
String s = "I am a Schemer!";
• Sometimes it can be useful to break up a
string into pieces.
I
am
tokens
a
Schemer!
String Tokenizer - Defining
• Steps to define a string tokenizer?
import java.util.*;
//must import this!
String s = "I am a Schemer!";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
• Output:
I
am
a
Schemer!
You can use other delimiters
other than spaces to tokenize
your strings.
JAVA Online
Ok..now you’re going to learn how to use the JAVA
API Documentation (ie. Java Online Help) to help you
do your labs.
The Java API Docs are available, nested deep in
www.java.sun.com…but let’s try closer to
home…since you all will be taking CS1102 next sem,
let’s go to the CS1102 webpage
http://www.comp.nus.edu.sg/~cs1102
JAVA Online
Once there, click on the “Resources” link. You will see
the link at the bottom- Java 2 Platform Std. Ed. v1.3.1
API Specification
This is the Java API Docs. You will also see other
links which enable you to download the API Docs
(very big - 23MB) and the Java Programming
Language (very big also - 26MB)
Okie…now click on the link to the Java API Docs ….
JAVA Online
On the left, you will see a list of all the classes
available in Java. Click on one of them, and you will
see all the information regarding that class - the
constructor, the methods and the properties
Notice that on the right panel, there’s a menu link at
the top - “Index” - this is very useful for searching for
anything regarding Java, such as methods, data types,
etc...
JAVA Online
Now, at the bottom left panel (Classes), find the String
class. Click on it and scroll thru the page to get a feel
of the online help looks like.
Okie now…a relevant exercise…you have been using
StringTokenizer…is there any way to count the
number of words in a sentence?
Getting Input from the User
• To do this, we use 2 classes:
BufferedReader & InputStreamReader.
• You need to import the input/output library
for this.
import java.io.*;
• The above code should be added to the start
of your main class file.
Getting Input from the User
• To get a line from the user and display the
text.
BufferedReader stdin =
new BufferedReader(
new InputStreamReader(System.in));
String tmp;
tmp = stdin.readLine();
System.out.println(tmp);
• Output:
Hello
Hello
Getting Input from the User
• You don’t need to define BufferedReader
every time you want to read a line.
• Just define it once, and then call readLine()
whenever you want to get input from the
user.
• Note: readLine() returns a String.
• What happens if you wish to read in
numbers?
Reading From a File
• Remember BufferedReader? We can use it
with FileInputStream to read data from
files.
FileInputStream infile =
new FileInputStream(“input.dat");
BufferedReader fin =
new BufferedReader(
new InputStreamReader(infile));
String currLine;
while ((currLine = fin.readLine()) != null) {
System.out.println(currLine); }
infile.close();
Writing to a File
• We use FileOutputStream & PrintWriter to
write to files.
FileOutputStream outfile =
new FileOutputStream("output.dat");
PrintWriter pw = new PrintWriter(outfile);
String currLine;
pw.println("I am a Schemer!");
pw.println("I\tam\ta\tSchemer\t!");
pw.flush();
outfile.close();
Some Other useful Functions
• Remainder
System.out.println(3 % 2);
• Random numbers
// returns r such that 0.0 <= r < 1
double r = Math.random();
• Rounding
System.out.println(Math.round("3.14159"));
• Parsing
int
i
double d
= Integer.parseInt("12345");
= Double.parseDouble("123.45");
Lab Question 1
Write a Java program that will let the user key in a string of numbers
separated by spaces. Then, separate the numbers, and store them in an array.
After that, go thru each number of the array and print out the number, at the
same time telling the user whether the number is a prime number.
import java.io.*;
import java.util.*;
class main
{
public static void main(String[] args) throws Exception
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String userinput = stdin.readLine();
StringTokenizer st = new StringTokenizer(userinput);
//fill in your code here
} //end method main
} //end class main
Lab Question 2
(in case you finish the 1st qn and want something to do :)
When you transit over to CS1102, you will find that most of the
programming assignments (actually in fact all) will require to
format your output, ie. display it in a nice format. This
sometimes require padding.
For strings, it will be the padding of spaces in front or at the
back of the string. For numbers, it will be the adding of zeros or
formatting the no. of decimal places (you will learn this number
formatting in CS1102. If you want, you can check out the
NumberFormat class)
Lab Question 2
(in case you finish the 1st qn and want something to do :)
Your program must first ask the user how many lines of input he
wishes to enter (let’s call it n). Then create an array of strings.
Then create a loop to keep asking the user for input until he has
keyed in n number of times. Inside the loop, you are to store his
input in the array.
Make all the strings the same length as the longest string in the
array by padding spaces in FRONT of the strings (check the
Java API under the String class to see how to check the length of
a string :)
Then, have a loop to print them all out. All your lines/strings
should be right-justified. If not, hee hee, it’s wrong ;-)
Some Other Online Help
• Scrooge
http://scrooge.comp.nus.edu.sg/jdk/docs/api/index.html
• Sun’s Java
http://java.sun.com
• Last last year’s Scheme->Conversion Course (1999)
http://www.comp.nus.edu.sg/~anthonyk/java