Presentation is loading. Please wait.

Presentation is loading. Please wait.

Scheme -> Java Conversion Course 2001 Lab Session 1/2.

Similar presentations


Presentation on theme: "Scheme -> Java Conversion Course 2001 Lab Session 1/2."— Presentation transcript:

1 Scheme -> Java Conversion Course 2001 Lab Session 1/2

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

3 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 resource- hungry and will take a longer time to load especially given the huge amount of students taking cs1102 with you :)

4 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

5 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!”); }

6 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!

7 Any problems? Check through your code again…remember Java is SUPER case- sensitive! helloWorld  HelloWorld! Any problems, raise your hands - your friendly seniors standing by :)

8 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?”); }

9 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)

10 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 :

11 EscapeEscapeCharacter SequenceSequenceRepresented Type Special\bBackspace \tHorizontal tab \nLinefeed \fForm feed \rCarriage return \”Double quotation mark (“) \’Single quotation mark (‘) \\Backslash

12 EscapeEscapeCharacter SequenceSequenceRepresented Type Octal\DDDCharacter 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\uHHHHCharacter 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

13 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";

14 Strings – Properties Strings are actually an array of characters. String s = "I am a Schemer!"; IamaSchemer! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 index What is the length of this string? 15

15 Strings – Extracting Characters String s = "I am a Schemer!"; int len = s.length(); char m = s.charAt(8); System.out.println(s.indexOf("Scheme"));// 7 System.out.println(s.substring(7));// Schemer! System.out.println(s.substring(7,13));// Scheme System.out.println(s.toLowerCase());// i am a schemer! System.out.println(s.toUpperCase());// I AM A SCHEMER! IamaSchemer! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

16 Strings – Comparing Strings Many times, you might need to compare 2 strings to see if they match. String s1 = "hello", s2 = "hallo"; if (s1.equals(s2)) { System.out.println("Equal!"); } else { System.out.println("Not Equal!"); } or use compareTo

17 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. IamaSchemer! tokens

18 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.

19 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

20 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 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 ….

21 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...

22 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?

23 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.

24 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

25 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?

26 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();

27 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();

28 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 = Integer.parseInt("12345"); double d = Double.parseDouble("123.45");

29 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

30 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)

31 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 ;-)

32 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


Download ppt "Scheme -> Java Conversion Course 2001 Lab Session 1/2."

Similar presentations


Ads by Google