First postgrad java version 2


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

First postgrad java version 2

  1. 1. Introduction to Programming using Java.
  2. 2. Introduction to Programming using Java. <ul><li>The aim of this course is to: </li></ul><ul><ul><li>Develop some programming skills using Java. </li></ul></ul><ul><ul><li>Apply the concepts of Programming and design using Java. </li></ul></ul><ul><li>Note that this is an elementary course. It only assumes basic competence in using a PC. </li></ul><ul><li>It assumes basic or no knowledge of Java </li></ul><ul><li>The course is however intensive - runs three hours a day for one whole week </li></ul><ul><li> Based on slides by Chris Bland and by Idris Ahmed </li></ul>
  3. 3. BOOK NOTICE for JAVA MODULES <ul><li>It is ESSENTIAL that you have a good reference text for this module. </li></ul><ul><li>A single text is no longer recommended as there are so many available. A set of texts and websites that you may find useful on the course website is listed on the course website: </li></ul><ul><li> </li></ul><ul><li>This should also be attached to you CUOnline Account. </li></ul><ul><li>Note the emphasis of the course in not on Java2 and does not include the swing classes or Java Beans. </li></ul>
  4. 4. Java sources <ul><li>‘ Teach yourself java in 21 Days’ – L. Lemay </li></ul><ul><li>‘ Thinking in Java’ – B. Eckel </li></ul><ul><li>‘ Java in a nutshell ‘ – D. Flanagan </li></ul><ul><li>‘ Introduction to programming using Java’ – D. M. Arnow </li></ul><ul><li>And many more … </li></ul><ul><li>In practice just go to: </li></ul><ul><li>and type ‘Java’ </li></ul>
  5. 5. Course Structure <ul><li>Any course in programming demands a lot of your own commitment and time. You will need the 120Hrs available to be able to study the course and complete the assignment. </li></ul><ul><li>The Structure of Week 1 of the course is: </li></ul><ul><ul><li>Lectures in Programming Features. </li></ul></ul><ul><ul><li>Practical work to try out what has been taught. </li></ul></ul><ul><li>The assessment has two components. </li></ul><ul><ul><li>In the second week there will be a “case study” given out for you to work on. This will contribute 20% of the module mark. At the end of the “assignment week” there will be an in-class ‘test’ which aims to examine your understanding of some of the fundamental issues. This comprises 80% of your mark. </li></ul></ul>
  6. 6. Why Java? <ul><li>Seen as being one of the major languages of the next few years. </li></ul><ul><li>Considered a simple language without many of the problems of C++ (e.g. memory leakage, pointers, arrays managing) </li></ul><ul><li>Based on the new philosophy of being Object Orientated. More and more languages and industrial applications are including OO features (e.g. Python, C#, J#, Visual J++). </li></ul><ul><li>Quite good documentation available online: </li></ul><ul><li> </li></ul><ul><li>(in practice just use google) </li></ul>
  7. 7. Why Java? <ul><li>Java is the language of the Internet and WWW. Programs can be run from WEB Browsers (e.g. IE, Firefox, Opera, Conqueror) </li></ul><ul><li>It has built-in security protection mechanisms. </li></ul><ul><li>It is machine independent. Surprisingly, this is unique! </li></ul><ul><li>You can create a Java program on a Linux or Apple Mac machine and it will run on Palm PC or Windows XP machine) </li></ul><ul><li>Java has protection to prevent it corrupting your machine should faults develop. Most languages do not have protection - system crashes can be catastrophic. </li></ul><ul><li>Java is library based. You can use code written anywhere in the world. Usually what you need is already in one of the libraries and the problem reduces only to finding it. </li></ul>
  8. 8. Java Beginnings <ul><li>There are two types of programs </li></ul><ul><ul><li>Application - which is free-standing. </li></ul></ul><ul><ul><li>Applet - which is invoked as part of a web page or Applet viewer. Applet is a small program with some build-in restrictions (e.g. can not touch your local hard drive). </li></ul></ul><ul><li>In this module the focus is on developing Applets. </li></ul>
  9. 9. Benefits of using Applets <ul><li>There exists no installation problem. The moment browser encounters Applet it is just loaded/installed automatically (user always gets the most recent version). </li></ul><ul><li>There are no problems with bad codes causing damage, since Java has in its core build-in protection mechanisms. Useful for Intranet purposes, i.e. company networks. </li></ul>
  10. 10. Borland’s Builder Java Development Kit. <ul><li>We will develop programs using an Integrated Development Environment (IDE). </li></ul><ul><li>This will combine all the functions of program development from editing, debugging, compiling to running. </li></ul><ul><li>Allows to correct potential errors on fly (e.g. syntax errors) </li></ul><ul><li>Gives hints regarding possible methods to be used </li></ul>
  11. 11. Software <ul><li>Java SDK (free GNU licence) </li></ul><ul><li>Webpage: </li></ul><ul><li>File name: j2sdk-1_4_2_16-windows-i586-p.exe </li></ul><ul><li>IDE </li></ul><ul><li>In class: JBuilder 8 - not free however available from most PCs on the University network </li></ul><ul><li>At home: Turbo JBuilder 2007 r2 (about 500 MB) - free trial version: </li></ul><ul><li>Alternative IDEs: </li></ul><ul><ul><li>Eclipse </li></ul></ul><ul><ul><li>Sun Netbeans </li></ul></ul><ul><ul><li>Intellij IDEA </li></ul></ul><ul><ul><li>IBM VisualAge </li></ul></ul><ul><ul><li>Microsoft.NET Framework </li></ul></ul>
  12. 12. Program Development Stages <ul><li>Editor - to type, change and save your program. </li></ul><ul><li>Compiler - converts the text into language the computer can understand. Java programs are converted into byte code . This is a ‘.class’ file . Byte code is an idealised language that can be understood by any computer that has an interpreter called Java Virtual Machine (JVM) . </li></ul>Editor Compiler Byte Code JVM Particular computer architecture
  13. 13. The Interpreter <ul><li>People have criticised Java because the ‘.class’ file is interpreted and hence can have a relative slow execution time. (About 20 times slower than C). </li></ul><ul><li>Java is interpreted because of the machine independence requirement which involves additional computational burden. </li></ul>
  14. 14. Applet viewer/browser <ul><li>To run our code we need to create a simple Web page which will invoke our Applet “.class” file </li></ul><ul><li>We need to use a html tag: </li></ul><ul><li><applet code = “Greeting.class” </li></ul><ul><li>width=300 height=200> </applet> </li></ul>
  15. 15. The Libraries <ul><li>The output from the compiler is saved in the form filename.class but is not yet complete. It needs to use libraries which contain already written programs. </li></ul><ul><li>To do this the relevant libraries are linked to the program when it is run. </li></ul><ul><li>This is done automatically for you. It saves them being downloaded from the web. </li></ul><ul><li>The compiler will check that the libraries you use are available on your system. </li></ul>
  16. 16. <ul><li>On your windows desktop click on “Start” </li></ul><ul><li>Then select “Programs” </li></ul><ul><li>Then select “Engineering Applications” </li></ul><ul><li>Then select “Borland JBuilder8” </li></ul><ul><li>This should automatically load the JBuilder </li></ul><ul><li>Close any potentially already opened projects! </li></ul><ul><li>On the Menu bar select “File” then “New” </li></ul><ul><li>A pop-up window like the one shown on the next slide appears. Select “Project” icon. </li></ul>GETTING STARTED
  19. 19. <ul><li>Having opened an empty project you need to upload a java file to get started. </li></ul><ul><li>On the left hand pane of the JBuilder IDE, click on the “Add to project” icon (a green plus sign) </li></ul><ul><li>A pop-up window will appear - use the “Look in” window to browse to the following shared drive: W:/EC/Student/M26SYS/Part 1/Lecture 1/1 </li></ul><ul><li>Select the “” file. </li></ul><ul><li>Select “File” and then “Save as” to save on your own network drive or USB stick </li></ul>GETTING STARTED
  20. 20. <ul><li>// This is the first program </li></ul><ul><li>import java.awt.*; </li></ul><ul><li>import java.applet.Applet; </li></ul><ul><li>public class Greeting extends Applet { </li></ul><ul><ul><li>public void paint(Graphics g){ </li></ul></ul><ul><ul><li>g.drawString(“Hello”,50,50); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>} </li></ul>First Program ‘’ Comment starts will ‘//’ Inclusion of packages used ‘ .*’ denotes all Class name the same as file name Function ‘paint’ is run automatically Invocation of Method ‘drawString’
  21. 21. To run a program <ul><li>There are several options here. One is to go to the Project menu and ‘Make Project’. This will compile the code. Then right click on the html file name and ‘Open in New Browser’ </li></ul><ul><li>Alternatively, you can use ‘Run using defaults’ . This is OK, but don’t forget to then view the html file and click the ‘Refresh’ icon at the top of the view pane. </li></ul><ul><li>Your program should run ! </li></ul><ul><li>When you change your code, don’t forget to rebuild it via the Project tab to ensure you are running the latest compiled version. </li></ul>
  22. 22. To be noted <ul><li>Each statement ends with semicolon ‘;’ i.e. g.drawString(“Hello”,50,50) ; </li></ul><ul><li>Number of brackets must be even. Each opening bracket, i.e. ‘{‘ must have an associated closing bracket ‘}’ , e.g . </li></ul><ul><ul><ul><li>public void paint(Graphics g) { </li></ul></ul></ul><ul><ul><ul><li>g.drawString(“Hello”,50,50); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><li>To make code easy to read use indents, e.g. </li></ul><ul><ul><ul><li>public class Greeting extends Applet { </li></ul></ul></ul><ul><ul><ul><li>public void paint(Graphics g){ </li></ul></ul></ul><ul><ul><ul><li>g.drawString(“Hello”,50,50); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  23. 23. <ul><li>Graphics are quite easy to do in Java. There are many ‘methods’ available. </li></ul><ul><li>Window size can be defined in the HTML file </li></ul><ul><li>Line Drawing: </li></ul><ul><ul><li>public void paint(Graphics g) { </li></ul></ul><ul><ul><li>g.drawLine(0,0,100,100); </li></ul></ul><ul><ul><li>} </li></ul></ul>Remark on graphics 1st x -coordinate 1st y - coordinate 2 nd x - coordinate 2 nd y - coordinate (0,0) Applet window x y
  24. 24. The Applet loading Process <ul><li>When a browser encounters a web page with Java it loads the classes over the network (may take some time) and runs the applet using the browser’s bytecode interpreter (which depends on the particular machine architecture). </li></ul><ul><li>The applet is run by creating ‘an instance’ of the applet class. </li></ul><ul><li>public void paint() we have seen is used to display data. </li></ul><ul><li>There are several stages in an applet’s operation: </li></ul><ul><ul><li>init() - the applet is first loaded. Called automatically to perform initialization of the applet. </li></ul></ul><ul><ul><li>start() - the reader is viewing the relevant page. Called automatically when the applet moves into sight on the Web page to start its operations. </li></ul></ul><ul><ul><li>stop() - another page is viewed. Called automatically when applet moves out of sight to shut off potentially expensive operations. </li></ul></ul><ul><ul><li>destroy() - used, for example, to clear memory. Called when applet is being unloaded from the page to perform final release of its resources. </li></ul></ul>
  25. 25. Variables (‘primitives’) <ul><li>byte : The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays , where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation </li></ul><ul><li>short : The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. </li></ul><ul><li>int : The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead. </li></ul><ul><li>long : The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. </li></ul><ul><li>float : The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this presentation. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the </li></ul><ul><li>double : The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this presentation. </li></ul><ul><li>boolean : The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its &quot;size&quot; isn't something that's precisely defined. </li></ul><ul><li>char : The char data type is a single 16-bit Unicode character. It has a minimum value of 'u0000' (or 0) and a maximum value of 'uffff' (or 65,535 inclusive). </li></ul>
  26. 26. <ul><li>Four integer types: </li></ul><ul><ul><ul><li>byte (8bit) 2^8 = 256 (why exactly 8 bits required?) </li></ul></ul></ul><ul><ul><ul><li>short (16bit) 2^16 = 65536 </li></ul></ul></ul><ul><ul><ul><li>int (32bit) 2^32 = 4294967296 </li></ul></ul></ul><ul><ul><ul><li>long (64bit) 2^64 ≈ 1.84467440737096 *10^19 </li></ul></ul></ul><ul><li>Variables need to be declared before usage, e.g. int myvar; byte cat; </li></ul><ul><li>Assignment is done with the usual ‘ =‘ parameter, e.g. myvar = 123; </li></ul><ul><li>Two real types: </li></ul><ul><li>- float (32bit) </li></ul><ul><li>- double (64bit) </li></ul><ul><li>e.g. float cash=23.6; double money=1.234e2 ; (which gives?) </li></ul><ul><li>Others: </li></ul><ul><ul><li>String mystring; mystring=“Alice has a cat”; </li></ul></ul><ul><ul><li>char mycharacter; char=‘e’; </li></ul></ul><ul><ul><li>boolean flag; boolean sensor=true; </li></ul></ul>
  27. 27. To be noted <ul><li>Names must begin with a letter, but can be any length. </li></ul><ul><li>Names of variables are case sensitive, i.e. </li></ul><ul><li>LENGTH, Length and length are DIFFERENT. </li></ul><ul><li>Before usage a variable must be declared. </li></ul><ul><li>Can be declared and initialized at the same time, e.g. </li></ul><ul><ul><li>int i = 10; </li></ul></ul><ul><ul><li>String mystring=“Alice has a cat”; </li></ul></ul>
  28. 28. Task for today (1) <ul><li>Go through the procedure described on slides and create your first project then add the file ‘’ into it. </li></ul><ul><li>Run it. </li></ul><ul><li>Make sure you are fine with the whole process of creating a new project in JBuilder. </li></ul>
  29. 29. Task for today (2) <ul><li>Modify the file ‘’ as follows: </li></ul><ul><li>Define and initialize two integers to store the (x,y) coordinates of where to display the text. </li></ul><ul><li>Define and initialize a variable of type String that will store the text to be displayed. </li></ul>
  30. 30. Task for today (3) <ul><li>Produce a code to print out the initial of your name, e.g. </li></ul><ul><ul><ul><ul><ul><li>TTTTTTTT L </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>T L </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>T L </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>T L </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>T LLLLLLL </li></ul></ul></ul></ul></ul><ul><li>Do not use spaces to format this, but enter the coordinates into drawString(). </li></ul><ul><li>Forgot how the method drawString() works? - find its description on web, i.e. type ‘drawString() java sun’ in google </li></ul>
  31. 31. Task for today (4) <ul><li>For this exercise you are asked to prepare a file containing the Java program shown below and then compile and run it. Then insert syntax errors and examine how the Java system responds. </li></ul><ul><li>The aim of this exercise is to introduce you to compiling and running Java programs and give you an opportunity to look at how the Java system responds to errors. The program is shown below: </li></ul><ul><ul><li>import java.awt.*; </li></ul></ul><ul><ul><li>import java.applet.Applet; </li></ul></ul><ul><ul><li>public class Fibonacci extends Applet { </li></ul></ul><ul><ul><li>int a, b, c; </li></ul></ul><ul><ul><li>public void paint(Graphics g){ </li></ul></ul><ul><ul><li>int i; </li></ul></ul><ul><ul><li>int[] fib = new int[10]; </li></ul></ul><ul><ul><li>fib[0] = 0; </li></ul></ul><ul><ul><li>fib[1] = 1; </li></ul></ul><ul><ul><li>for(i = 2; i<10;i++){ </li></ul></ul><ul><ul><li>fib[i] = fib[i-1] + fib[i-2]; </li></ul></ul><ul><ul><li>g.drawString(&quot;Fibonacci [&quot; + i +&quot;] - &quot; + fib[i],50,(i*10)+50); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>Font f=new Font(&quot;TimesRoman&quot;,Font.BOLD,14); g.setFont(f); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color.RED); </li></ul></ul><ul><ul><li>g.drawString(&quot;Fibonacci numbers&quot;, 50, 20); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  32. 32. <ul><li>Make a project and type the program into JBuilder. Run it and examine the results. Don't forget that Java is case sensitive. </li></ul><ul><li>You should see: </li></ul><ul><li>Fibonacci [2] - 1 </li></ul><ul><li>Fibonacci [3] - 2 </li></ul><ul><li>Fibonacci [4] - 3 </li></ul><ul><li>Fibonacci [5] - 5 </li></ul><ul><li>Fibonacci [6] - 8 </li></ul><ul><li> … etc. </li></ul><ul><li>Now apply a number of changes to the code, one at a time. The changes are described below. After each change, compile the code and examine the error messages that have been produced by the compiler. After you have examined the error message, modify the code so that it returns to its original correct state. When it has returned to this state apply the next syntax error. Adopt this procedure so that you do not see the effect of a number of syntax errors at once. </li></ul><ul><li>The changes to apply are as follows: </li></ul><ul><li>delete a semi-colon which terminates a statement; </li></ul><ul><li>replace the first occurrence of the variable name ‘i’ by the variable name ‘in’; </li></ul><ul><li>delete the declaration of the ‘int’ variable ‘i’; </li></ul><ul><li>replace the keyword ‘class’ with ‘Class’; </li></ul><ul><li>replace the keyword ‘for’ by the keyword ‘form’; </li></ul><ul><li>and delete one of the final curly brackets. </li></ul>Task for today (4)
  33. 33. Lecture 2
  34. 34. Recap <ul><li>Fully object oriented (OO) language </li></ul><ul><li>Platform independent (byte code) </li></ul><ul><li>Program = Applet or Application </li></ul><ul><li>Variables (primitives) </li></ul><ul><li>IDE – JBuilder 8 (project etc.) </li></ul>
  35. 35. Exemplary Drawing Methods <ul><li>drawRect(XtopLeft,YtopLeft,width,height); </li></ul><ul><li>drawOval(XtopLeft,YtopLeft,width,height); </li></ul><ul><li>drawArc(XtopLeft,YtopLeft,width,height, </li></ul><ul><li>startAngle,totalAngle); </li></ul><ul><li>setBackground(; </li></ul><ul><li>g.setColor(java.awt.Color. WHITE ); </li></ul><ul><li>etc. </li></ul>
  36. 36. 1D arrays <ul><li>Array is a set of variables of the same type packaged together under one name, e.g. </li></ul><ul><ul><li>int [] tab1; </li></ul></ul><ul><ul><li>boolean [] tab2; </li></ul></ul><ul><li>Arrays are defined and used with the operator ‘[]’ </li></ul><ul><li>Note that above arrays are only declared and not defined yet and so there has been no space allocated for the array. </li></ul>
  37. 37. 1D arrays <ul><li>Arrays can be defined in two ways: </li></ul><ul><ul><li>At the step of their declaration using ‘{ }’ , e.g. </li></ul></ul><ul><ul><li>int[] tab1={1, 2, 3, 4, 5}; </li></ul></ul><ul><ul><li>boolean[] tab2={true, false, true, false}; </li></ul></ul><ul><ul><li>Or later in the code using ‘[ ]’ , e.g. </li></ul></ul><ul><ul><ul><li>tab1[0]=1; tab2[0]=true; </li></ul></ul></ul><ul><ul><ul><li>tab1[1]=2; tab2[1]=false; </li></ul></ul></ul><ul><ul><ul><li>tab1[2]=3; tab2[2]=true; </li></ul></ul></ul><ul><ul><ul><li>tab1[3]=4; tab2[3]=false; </li></ul></ul></ul><ul><ul><ul><li>tab1[4]=5; </li></ul></ul></ul>
  38. 38. <ul><li>Indexing starts from index 0 ! </li></ul><ul><li>5 element array </li></ul><ul><li>Items are indexed from 0 to 4 (exclusively) </li></ul><ul><li>Arrays can store variables e.g. </li></ul><ul><ul><li>int x=50, y=90; </li></ul></ul><ul><ul><li>int[] tab = {x,y}; </li></ul></ul>1D arrays tab1[0] tab1[1] tab1[2] tab1[3] tab1[4] 1 2 3 4 5 Array ‘tab1’
  39. 39. Drawing a Polygon using arrays <ul><li>int[] exes ={34,67,45,23}; </li></ul><ul><li>int[] whys ={45,78,84,67}; </li></ul><ul><li>int pts = 4; </li></ul><ul><li>g.drawPolygon(exes,whys,pts); </li></ul><ul><li>g.fillPolygon(exes,whys,pts); </li></ul>
  40. 40. Fonts <ul><li>Java has a range of fonts available. However, you need to take care that the browser will understand them. </li></ul><ul><li>First you need to declare the font you want to use: </li></ul><ul><li>Font f=new Font(“TimesRoman”,Font.BOLD,24); </li></ul><ul><li>Then type: g.setFont(f); </li></ul>
  41. 41. Passing Parameters to Applets <ul><li><APPLET CODE = “MyClass.class” WIDTH=300 HEIGHT=300> </li></ul><ul><li><PARAM NAME=size VALUE =“36”> </li></ul><ul><li></APPLET> </li></ul><ul><li>Parameters are passed to the applet when it is loaded. They can be read by using the ‘getParameter’ method: </li></ul><ul><li>mySize=getParameter(“size”); </li></ul><ul><li>This would normally be done as part of the code in init(). </li></ul>
  42. 42. Calculations <ul><li>Standard operators apply, i.e. ‘+’, ’-’, ‘/’, ‘*’,’^’. </li></ul><ul><li>Note - increment can be done by say: i=i+1; or i++; </li></ul><ul><li>Parenthesis should be used to avoid ambiguity when doing long calculations,e.g. </li></ul><ul><li>result = ( ( 1+2 ) / ( 3+4 ) ) * ( 5/6 ) ^7; </li></ul>
  43. 43. Examples <ul><li>The ‘%‘ operator used to produce remainders. </li></ul><ul><li>a=12 % 4; a=13 % 4; a=15 % 4; </li></ul><ul><li>In the case of real types use ‘.0f’ , e.g. </li></ul><ul><ul><ul><li>float f; </li></ul></ul></ul><ul><ul><ul><li>f = 7 / 2; // ( gives 3 ) </li></ul></ul></ul><ul><ul><ul><li>f = 7 .0f / 2 .0f ; // (gives 3.5) </li></ul></ul></ul><ul><li>Initialization of floats – use ‘f’ , e.g. </li></ul><ul><li>float f1 = 4.5; // ( error ) </li></ul><ul><li>float f1 = 4.5 f ; </li></ul>
  44. 44. Mixing Data Types. <ul><li>It is common to want to write expressions which mix data types, e.g: </li></ul><ul><ul><ul><li>float value1=5, value2=2, average; </li></ul></ul></ul><ul><ul><ul><li>average = (value1+value2)/2; </li></ul></ul></ul><ul><li>This float-integer mix will work fine, but, not all will, e.g. say average is an integer, i.e. </li></ul><ul><ul><ul><li>float value1=5, value2=2; </li></ul></ul></ul><ul><ul><ul><li>int average; </li></ul></ul></ul><ul><ul><ul><li>average = (value1+value2)/2; </li></ul></ul></ul><ul><li>The idea is to try not to lose information. Only so-called narrowing conversions possible. In the case of widening conversions an explicit cast is not required. </li></ul>
  45. 45. ‘ Overcoming’ the Limitation of Data Types <ul><li>Fine (widening conversion): </li></ul><ul><ul><li>int i=10; float f=i; </li></ul></ul><ul><li>Error (narrowing conversion): </li></ul><ul><ul><li>float f=10.5f; int i=f; // needs to be done explicitly </li></ul></ul><ul><li>Casting concept – work but precision is lost: </li></ul><ul><ul><li>float f; int i = (int) f; </li></ul></ul><ul><li>Casting done using ‘(x)’, where ‘x’ is the variable type on which to cast (or project to), e.g. </li></ul><ul><li>Example: </li></ul><ul><ul><li>float f=10.1234f; int i=(int)f; // gives 10 </li></ul></ul>
  46. 46. Type Conversion Example <ul><li>int ivalue =33; float fvalue =3.9f; int i; </li></ul><ul><li>float x; double d; </li></ul><ul><ul><ul><ul><ul><li>1: x=ivalue; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>2 : i=fvalue; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>3: i=(int) fvalue; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>4 : i=(float) fvalue; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>5 : i=(double) fvalue; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>6: x=(int) (10+11)/2; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>7: x=(float) (10+11)/2; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>8: d=x; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>9 : x=d; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>10 : x=(double)d; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>11: x=(float)d; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>12: d=(float)i; </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>13 : x=ivalue </li></ul></ul></ul></ul></ul>
  47. 47. Mathematics Library <ul><li>Part of the power of Java comes from its extensive libraries. One of these is the Maths library. </li></ul><ul><li>Many standard scientific mathematical processes are defined in the library java.lang.Math; </li></ul><ul><li>One way to use this library is to call the required function directly, e.g. </li></ul><ul><ul><li>double a=Math.sqrt(2*4*8); // square root of 64 = 8 </li></ul></ul><ul><ul><li>double b=Math.pow(2,8); // 2 to power of 8, i.e. 2^8 = 256 </li></ul></ul><ul><ul><li>double c=Math.abs(-123); // absolute value of | -128 | = 128 </li></ul></ul><ul><ul><li>double d=Math.exp(1.23); // Euler’s number ^1.23, i.e. 2.7 ^ 1.23 </li></ul></ul><ul><li>More functions can be found at: </li></ul><ul><li> </li></ul>
  48. 48. Methods <ul><li>Allows the program to be split into logical chunks </li></ul><ul><li> type returned method name ( parameter1, parameter2, … ) </li></ul><ul><li> e.g. </li></ul><ul><li>void drawString ( String str, int x, int y ) </li></ul><ul><li>Once defined we can use it by just giving its name and its parameters, e.g. </li></ul><ul><ul><li>drawString(“Alice”,50,50); </li></ul></ul><ul><ul><li>drawString(“Cat”,50,80); </li></ul></ul><ul><li>Must be defined before usage </li></ul>
  49. 49. Method definition <ul><li>import java.awt.*; </li></ul><ul><li>import java.applet.Applet; </li></ul><ul><li>public class Alice extends Applet { </li></ul><ul><ul><li>public String myMethod ( int x, int y, String s, Graphics g){ </li></ul></ul><ul><ul><li>g.drawString(s,x,y); </li></ul></ul><ul><ul><li>g.drawRect(x-20, y-20, s.length()*15, 40); </li></ul></ul><ul><ul><li>return s+&quot; has a cat&quot;; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>public void paint(Graphics g){ </li></ul></ul><ul><ul><li>String q= myMethod (50,50,&quot;Alice&quot;,g); </li></ul></ul><ul><ul><li>g.drawString(q,10,150); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>} </li></ul>
  50. 50. Tasks for today (1) <ul><li>Compute using Math library the following expression </li></ul>
  51. 51. Tasks for today (2) <ul><li>Create the following applet: </li></ul>
  52. 52. Tasks for today (2) <ul><li>Methods to be used: </li></ul><ul><ul><li>setBackground </li></ul></ul><ul><ul><li>g.setColor </li></ul></ul><ul><ul><li>g.drawString </li></ul></ul><ul><ul><li>g. setFont </li></ul></ul><ul><ul><li>g.drawLine </li></ul></ul><ul><ul><li>g.drawRect </li></ul></ul><ul><ul><li>g.drawOval </li></ul></ul><ul><ul><li>g.drawArc </li></ul></ul><ul><ul><li>g.drawRoundRect </li></ul></ul><ul><ul><li>g.drawPolygon </li></ul></ul><ul><ul><li>g.fillPolygon </li></ul></ul><ul><ul><li>g.fillOval </li></ul></ul>Method not known? - type in google ‘ fillOval java sun’ and get information
  53. 53. Tasks for today (3) <ul><li>Define and implement a method that will compute and display the following mathematical expression for any passed parameters x and y , i.e. </li></ul><ul><li>double d = myMethod(1.23f, 4.56f); </li></ul>
  54. 54. Task 1 <ul><li>public void paint(Graphics g){ </li></ul><ul><ul><li>double a1, a2, a3, a4, outcome; </li></ul></ul><ul><ul><li>a1 =Math.pow(Math.E,(Math.PI*Math.log(Math.PI*Math.E))); </li></ul></ul><ul><ul><li>a2 =Math.tan(Math.atan(Math.PI/4)*Math.sin(Math.PI/2)); </li></ul></ul><ul><ul><li>a3 =Math.pow( Math.asin(1) + Math.cos(2*Math.PI),-1.234 ); </li></ul></ul><ul><ul><li>a4 =Math.abs( -Math.PI*Math.sqrt(Math.pow(Math.PI,Math.PI)) ); </li></ul></ul><ul><ul><li>outcome = Math.min( a1 , a2 ) * Math.max( a3 , a4 ); </li></ul></ul><ul><ul><li>g.drawString(“Result is: ”+outcome); </li></ul></ul><ul><li>} </li></ul>
  55. 55. Task 2 <ul><li>public void paint(Graphics g) { </li></ul><ul><ul><li>// background </li></ul></ul><ul><ul><li>setBackground(java.awt.Color. LIGHT_GRAY ); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. YELLOW ); </li></ul></ul><ul><ul><li>// text string </li></ul></ul><ul><ul><li>g.drawString(&quot;Hello there!&quot;,100,50); </li></ul></ul><ul><ul><li>Font f= new Font(&quot;TimesRoman&quot;,Font. BOLD ,24); </li></ul></ul><ul><ul><li>g.setFont(f); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. BLACK ); </li></ul></ul><ul><ul><li>g.drawString(&quot;Hello there!&quot;,200,150); </li></ul></ul><ul><ul><li>// lines </li></ul></ul><ul><ul><li>g.drawLine(0,0,200,100); </li></ul></ul><ul><ul><li>g.drawLine(0,100,200,0); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. BLUE ); </li></ul></ul><ul><ul><li>// rectangle </li></ul></ul><ul><ul><li>g.drawRect(0, 0, 200, 100); </li></ul></ul><ul><ul><li>// ellipse </li></ul></ul><ul><ul><li>g.drawOval(0, 0, 200, 100); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. BLUE ); </li></ul></ul>
  56. 56. <ul><ul><li>// arcs to build coloured circle </li></ul></ul><ul><ul><li>g.drawArc(200, 200, 100, 100, 0, 90); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. RED ); </li></ul></ul><ul><ul><li>g.drawArc(200, 200, 100, 100, 90, 90); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. GREEN ); </li></ul></ul><ul><ul><li>g.drawArc(200, 200, 100, 100, 180, 90); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. MAGENTA ); </li></ul></ul><ul><ul><li>g.drawArc(200, 200, 100, 100, 270, 90); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. RED ); </li></ul></ul><ul><ul><li>// round rectangle </li></ul></ul><ul><ul><li>g.drawRoundRect(10, 120, 150, 120, 45, 45); </li></ul></ul><ul><ul><li>// arrays for x and y coordinates </li></ul></ul><ul><ul><li>int [] xs = { 40+300, 50+300, 80+300, 50+300, 40+300, 30+300, 300, 30+300 }; </li></ul></ul><ul><ul><li>int [] ys = { 0, 30, 40, 50, 80, 50, 40, 30 }; </li></ul></ul><ul><ul><li>// polygons </li></ul></ul><ul><ul><li>g.drawPolygon(xs, ys, 8); </li></ul></ul><ul><ul><li>g.fillPolygon(ys, xs, 8); </li></ul></ul><ul><ul><li>g.fillOval(300+30, 30, 20, 20); </li></ul></ul><ul><ul><li>g.setColor(java.awt.Color. WHITE ); </li></ul></ul><ul><ul><li>g.fillOval(30, 300+30, 20, 20); </li></ul></ul><ul><li>} </li></ul>
  57. 57. Task 3 <ul><li>import java.awt.*; </li></ul><ul><li>import java.applet.Applet; </li></ul><ul><li>public class Greetings extends Applet { </li></ul><ul><li>double myMethod( double x, double y){ </li></ul><ul><ul><li>double num = Math.pow(Math.E,x) + Math.pow(Math.PI,y); </li></ul></ul><ul><ul><li>double den = Math.sin(x) - Math.cos(y); </li></ul></ul><ul><ul><li>return num / den; </li></ul></ul><ul><li>} </li></ul><ul><li>public void paint(Graphics g){ </li></ul><ul><ul><li>double d = myMethod(1.0f,1.5f); </li></ul></ul><ul><ul><li>g.drawString(&quot;x=1.0 y=1.5 :&quot;+d,20,30); </li></ul></ul><ul><ul><li>d = myMethod(10.0f,1.5d); </li></ul></ul><ul><ul><li>g.drawString(&quot;x=10 y=1.5 :&quot;+d,20,50); </li></ul></ul><ul><ul><li>d = myMethod(1,15f); </li></ul></ul><ul><ul><li>g.drawString(&quot;x=1.0 y=15 :&quot;+d,20,70); </li></ul></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  58. 58. Lecture 3
  59. 59. Recap <ul><li>Mathematical operations (java.lang.Math) </li></ul><ul><li>1D arrays </li></ul><ul><li>Drawing methods (java.awt.Graphics) </li></ul><ul><li>Conversion between different types </li></ul><ul><li>Methods </li></ul>
  60. 60. Decision Making <ul><li>We cannot develop programs of any complexity using sequential programming. </li></ul><ul><li>We need to able to make decisions and structure the program based on the results of an event or calculation. </li></ul><ul><li>This section shows how this can be achieved. </li></ul>
  61. 61. Control Structures IF <ul><li>Structure: </li></ul><ul><li>if ( condition ) statement ; </li></ul><ul><li>e.g. </li></ul><ul><li>if (c==12 ) signal=true; </li></ul><ul><ul><li>if (age > 21) { </li></ul></ul><ul><ul><li>g.drawString(“Sell alcohol”,10,10); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>if (age <= 21) { </li></ul></ul><ul><ul><li>g.drawString(“Do not sell alcohol”,10,10); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>When statement comprises more commands use ‘{ }’ , e.g. </li></ul><ul><ul><li>if (a==1) { </li></ul></ul><ul><ul><li>h=12; </li></ul></ul><ul><ul><li>c=“new employee”; </li></ul></ul><ul><ul><li>g.drawString(c,10,10); </li></ul></ul><ul><ul><li>} </li></ul></ul>
  62. 62. Control Structures IF-ELSE <ul><li>Structure: </li></ul><ul><li>if ( condition ) statement1; else statement2; </li></ul><ul><li>e.g. </li></ul><ul><ul><li>if (age > 21) </li></ul></ul><ul><ul><li>g.drawString(“Sell alcohol”,10,10); </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>g.drawString(“Do not sell alcohol”,10,10); </li></ul></ul><ul><ul><li>if (age > 21) { </li></ul></ul><ul><ul><li>g.drawString(“Sell alcohol”,10,10); </li></ul></ul><ul><ul><li>police = false; </li></ul></ul><ul><ul><li>} else { </li></ul></ul><ul><ul><li>g.drawString(“Do not sell alcohol”,10,10); </li></ul></ul><ul><ul><li>police = true; </li></ul></ul><ul><li> } </li></ul>
  63. 63. Relational and logical operators outcome is true/false <ul><li>Relations </li></ul><ul><li>> greater than </li></ul><ul><li>< less than </li></ul><ul><li>>= greater than or equal </li></ul><ul><li><= less than or equal </li></ul><ul><li>== equal </li></ul><ul><li>!= not equal </li></ul><ul><li>Logic </li></ul><ul><li>!x not x </li></ul><ul><li>x && y x and y </li></ul><ul><li>x || y x or y </li></ul>
  64. 64. Truth tables for logical operators not x !x x and y x && y x or y x || y T – true (1) F – false (0)
  65. 65. Some examples <ul><li>boolean b; </li></ul><ul><li>b = 5 > 6; </li></ul><ul><li>b = !(5>6); </li></ul><ul><li>b = (5 > 6) || (5 < 6); </li></ul><ul><li>b = (4 >= 5); </li></ul><ul><li>b = (5 >= 5); </li></ul><ul><li>b = (5 > 6) && ( 5 > 6); </li></ul><ul><li>b = !( (9 <= 9 ) && ( 5 < 1) ) && (0 < 1); </li></ul>
  66. 66. Example <ul><li>if (age > 0 && age < 7){ </li></ul><ul><li>s = “child”; </li></ul><ul><li>}else{ </li></ul><ul><li>if (age >= 7 && age < 18 ){ </li></ul><ul><li>s = “teenager”; </li></ul><ul><li>}else{ </li></ul><ul><li>s = “adult”; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  67. 67. Example <ul><li>if ( (age > 18) && (hasDrivingLicense==true || hasID==true) ){ </li></ul><ul><li>b = “can enter a pub”; </li></ul><ul><li>}else{ </li></ul><ul><li>b = “can not enter a pub”; </li></ul><ul><li>} </li></ul>
  68. 68. Control Structure SWITCH <ul><li>Instead of nesting if statement with ‘==‘ operator just use ‘switch’ : </li></ul><ul><li>switch ( expression ) { </li></ul><ul><ul><li>case constant-1 : statements-1 break; </li></ul></ul><ul><ul><li>case constant-2 : statements-2 break; </li></ul></ul><ul><ul><li>. . . // (more cases) </li></ul></ul><ul><ul><li>default: // optional default case </li></ul></ul><ul><ul><li>default statements </li></ul></ul><ul><li>} </li></ul>
  69. 69. Control Structure SWITCH <ul><li>switch (N) { // assume N is an integer variable </li></ul><ul><li>case 1: g.drawString(&quot;The number is 1“,10,10); break; </li></ul><ul><li>case 2: g.drawString(&quot;The number is 2“,10,10); break; </li></ul><ul><li>case 3: g.drawString(&quot;The number is 3&quot;,10,10); break; default: g.drawString(“Outside the range 1 to 3“,10,10); </li></ul><ul><li>} </li></ul>
  70. 70. Control Structures SWITCH <ul><li>Remember about the ‘break’ keyword </li></ul><ul><li>switch (N) { // assume N is an integer variable </li></ul><ul><li>case 1: </li></ul><ul><li>case 2: </li></ul><ul><li>case 3: g.drawString(&quot;The number is 1 or 2 or 3&quot;,10,10); break; </li></ul><ul><li>case 4: g.drawString(&quot;The number is 4&quot;,10,10); break; </li></ul><ul><li>default: g.drawString(“Outside the range 1 to 4“,10,10); </li></ul><ul><li>} </li></ul>
  71. 71. Control Structures SWITCH <ul><li>Remember about the ‘break’ keyword </li></ul><ul><li>switch (N) { // assume N is an integer variable </li></ul><ul><li>case 1: break; </li></ul><ul><li>case 2: </li></ul><ul><li>case 3: g.drawString(&quot;The number is 2 or 3&quot;,10,10); break; </li></ul><ul><li>case 4: g.drawString(&quot;The number is 4&quot;,10,10); break; </li></ul><ul><li>default: g.drawString(“Outside the range 1 to 4“,10,10); </li></ul><ul><li>} </li></ul>
  72. 72. Repetition - while, for and do. <ul><li>To do a certain task several times we use loops </li></ul><ul><li>There are three possibilities: </li></ul><ul><li>‘ for’ , ‘while’ and ‘do’-’while’ </li></ul><ul><ul><li>for (i=1; i<10; i++){ </li></ul></ul><ul><ul><li>//statement </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>i=1; </li></ul></ul><ul><ul><li>while (i<10){ </li></ul></ul><ul><ul><li>//statement </li></ul></ul><ul><ul><li>i++; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>i=1; </li></ul></ul><ul><ul><li>do { </li></ul></ul><ul><ul><li>//statement </li></ul></ul><ul><ul><li>i++; </li></ul></ul><ul><ul><li>} while (i<10); </li></ul></ul>
  73. 73. Example <ul><li>// T - letter </li></ul><ul><li>for (i=1;i<10;i++){ </li></ul><ul><li>g.drawString(&quot;x&quot;,50,10+i*10); </li></ul><ul><li>} </li></ul><ul><li>for (i=1;i<10;i++){ </li></ul><ul><li>g.drawString(&quot;x&quot;,i*10,10); </li></ul><ul><li>} </li></ul><ul><li>// L - letter </li></ul><ul><li>for (i=1;i<10;i++){ </li></ul><ul><li>g.drawString(&quot;x&quot;,110,10+i*10); </li></ul><ul><li>} </li></ul><ul><li>for (i=1;i<10;i++){ </li></ul><ul><li>g.drawString(&quot;x&quot;,100+i*10,110); </li></ul><ul><li>} </li></ul>
  74. 74. Example <ul><li>int [] tab = {0, 10, 20, 30, 40} ; </li></ul><ul><li>for ( int i=0; i<5 ;i++){ </li></ul><ul><li>g.drawString(&quot;Index :&quot;+i+&quot; value :&quot;+tab[i],10,20*i); </li></ul><ul><li>} </li></ul><ul><li>for ( int i=4; i>-1 ;i--){ </li></ul><ul><li>g.drawString(&quot;Index :&quot;+i+&quot; value :&quot;+tab[i],10,20*i); </li></ul><ul><li>} </li></ul>
  75. 75. Example <ul><li>To define size of array after its declaration use operator ‘new’ </li></ul><ul><li>int[] tab; </li></ul><ul><li>int size = 5; </li></ul><ul><li>tab = new int[size]; </li></ul><ul><li>for (int i=0; i<size; i++){ </li></ul><ul><li>tab[i] = i*10; </li></ul><ul><li>} </li></ul><ul><li>Length of particular array can be obtained by using ‘length’ , e.g. </li></ul><ul><li>for (int i=0; i<tab. length ; i++){ </li></ul><ul><li>tab[i] = i*10; </li></ul><ul><li>} </li></ul><ul><li>Note that ‘length’ is not a method but attribute of any array variable (methods always end with brackets) </li></ul>
  76. 76. 2D arrays <ul><li>Enables grids to be represented. </li></ul><ul><li>The use is really just as in 1D arrays, but uses two sets of ‘[]’ , i.e. ‘[][]’ </li></ul><ul><li>Declaration: </li></ul><ul><li>int [][] sales = new int [4][3]; </li></ul><ul><li>String [][] chessboard = new String [7][7]; </li></ul><ul><li>First element rows, second columns. </li></ul><ul><li>Image is an example of 2D array </li></ul>
  77. 77. Example <ul><li>int[][] tab = new int[2][3]; </li></ul><ul><li>int column, row; </li></ul><ul><li>int i = 1; </li></ul><ul><li>for (column=0; column<3; column++){ </li></ul><ul><li>for (row=0; row<2; row++){ </li></ul><ul><li>tab[row][column] = i; </li></ul><ul><li>i++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>1 3 5 2 4 6
  78. 78. Example <ul><li>int[][] tab = new int[2][3]; </li></ul><ul><li>int column, row; </li></ul><ul><li>int i = 1; </li></ul><ul><li>for (row=0; row<2; row++){ </li></ul><ul><li>for (column=0; column<3; column++){ </li></ul><ul><li>tab[row][column] = i; </li></ul><ul><li>i++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>2 3 </li></ul><ul><li>4 5 6 </li></ul>
  79. 79. Tasks – part 1 <ul><li>Write and test a method that takes two integers as parameters and determines whether the second number is a multiple of the first. </li></ul><ul><li>Write a method that determines if the number used as a parameter is a prime number. </li></ul><ul><li>Write a program that determines the cost of a letter given its weight. Check the overall cost of sending letters of the weights: 11, 23, 89, 135, 112. The postage rate for letters is: </li></ul><ul><li>Develop a program to determine the solution to a quadratic equation. Use methods to determine positive and negative roots. </li></ul>
  80. 80. Tasks – part 2 * <ul><li>1. A common task is to develop a piece of code to will sort through a set of integers held in an array into numerical order. Write a simple algorithm that could achieve this. </li></ul><ul><li>2. In the mathematical theory of sets, a set is defined as a collection of distinct items of the same type. The aim of this exercise is to develop methods for the functions of set union, intersection and difference. </li></ul><ul><ul><li>The union of two sets is a set which contains the elements that are in both sets. </li></ul></ul><ul><ul><li>The intersection of two sets is a set that contains elements common to both sets. </li></ul></ul><ul><ul><li>The difference of two sets is a set that contains the elements which are in the first, but not the second. </li></ul></ul><ul><li>Example: Given two sets of integers {5,7,8,10} and {3,9,10} </li></ul><ul><li>Union: {3,5,7,8,9,10} Intersection: { 10} Difference: {5,7,8} </li></ul><ul><li>Develop a program that generates two random set of integers in the range 0-50 and stores them in two arrays of ten elements. Display each of the sets. Ensure each array does not contain duplicate values. Display the results of each of the methods. </li></ul><ul><li>HINT </li></ul><ul><li>To generate a random number we can use the random method in the Maths class. This can be used by simply calling: </li></ul><ul><li>Math.random(); </li></ul><ul><li>The result is a number between 0 and 0.9999. </li></ul><ul><li>If you wanted to generate a number between 1 and 6 you need to scale the result by: </li></ul><ul><li>number= (int) (Math.random()*6)+1; </li></ul>
  81. 81. Characters <ul><li>Mainly used for text handling - input and output. </li></ul><ul><li>A single character type is allowed called char. </li></ul><ul><li>Char is a primitive type used as any other variable: </li></ul><ul><li>char inital = ‘M’; // note single quotes. </li></ul><ul><li>char marker= ‘n’; // this means new line. </li></ul><ul><li>char tab=‘t’; // tab </li></ul>
  82. 82. Character Operations <ul><li>Comparisons can be made as usual: </li></ul><ul><li>if (initial == ‘s’) ....... </li></ul><ul><li>Letters are actually stored in an order and so we can compare ranges: </li></ul><ul><li>if ((initial>=‘0’)&&(initial<=‘9’)) // test for a digit </li></ul><ul><ul><li>if ((initial>=‘A’)&&(initial<=‘Z’)) // test for upper case </li></ul></ul>
  83. 83. String Class <ul><li>String is not a primitive type, but an object and so </li></ul><ul><li>to use it we must use our usual way of calling the </li></ul><ul><li>methods defined within String. </li></ul><ul><li>There are actually two string classes String and StringBuffer. </li></ul>
  84. 84. String Features. <ul><li>Declaration: </li></ul><ul><li>String myName =“Fred”; </li></ul><ul><li>Assignment: </li></ul><ul><li>x=“England; </li></ul><ul><li>y=x; z=““; </li></ul><ul><li>append=append+”a string”; </li></ul>
  85. 85. String Operations <ul><li>Comparisons are achieved using methods of </li></ul><ul><li>the class String eg: </li></ul><ul><li>if (x.equals(y)) ………. </li></ul><ul><li>Arrays of strings can be created: </li></ul><ul><li>String cities[] = new String[10]; </li></ul><ul><li>cities[1]=“London”; </li></ul>
  86. 86. String Methods for Comparison <ul><li>We can not test for two Strings being equal using ==. </li></ul><ul><li>This is because a String is an object and hence can have several variables attached to it. In which case what are we comparing? </li></ul><ul><li>Instead comparison is done using methods within the String class. </li></ul><ul><li>equals: </li></ul><ul><li>if (string1.equals(string2)) </li></ul><ul><li>result = “They are equal”; </li></ul><ul><li>equalsIgnoreCase : </li></ul><ul><li>Used as above, but ignores case of letters. </li></ul>
  87. 87. String Comparison with compareTo method <ul><li>Enables strings to be ordered alphabetically or according to </li></ul><ul><li>the case - upper is treated as larger. </li></ul><ul><li>compareTo returns an integer according to the rules: </li></ul><ul><li>0 if the strings are equal </li></ul><ul><li>-ve if the strings are in order </li></ul><ul><li>+ve if the strings are out of order </li></ul>
  88. 88. Examples: <ul><li>n=“ant”.compareTo(“bee”); // n is -ve </li></ul><ul><li>int n=string1.compareTo(string2); </li></ul><ul><li>if (n==0) </li></ul><ul><li>result=“They are equal”; </li></ul><ul><li>else if (n<0) </li></ul><ul><li>result = “string1 precedes string2”; </li></ul><ul><li>else </li></ul><ul><li>result = “string2 precedes string1”; </li></ul>
  89. 89. Ammending Strings <ul><li>replace: </li></ul><ul><li>string1 = “Landan”.replace(‘a’,’o’); // gives string1=London. Only works for single characters </li></ul><ul><li>toLowerCase: </li></ul><ul><li>result = string1.toLowerCase(); </li></ul><ul><li>toUpperCase </li></ul><ul><li>trim: </li></ul><ul><li>string1=“ Spaces”; </li></ul><ul><li>result = string1.trim(); // gives result = “Spaces” </li></ul>
  90. 90. Examining Strings <ul><li>length: </li></ul><ul><li>int n = “String Length”.length(); // n =13 </li></ul><ul><li>substring: </li></ul><ul><li>string1 = “position”; </li></ul><ul><li>result = string1.substring(2,5); // gives result = “sit” </li></ul><ul><li>charAt: </li></ul><ul><li>char c1,c2; </li></ul><ul><li>string = “position”; </li></ul><ul><li>c1 = string1.charAt(1); // gives c1= ‘o’ </li></ul><ul><li>c2 = string1.charAt(4); // gives c2=‘t’ </li></ul>
  91. 91. Examining Strings 2 <ul><li>indexOf: </li></ul><ul><li>Searches for substrings. </li></ul><ul><li>int n = “mississippi”.indexOf(“is”,4); </li></ul><ul><li>Looks for “is” from forth numbered character. </li></ul><ul><li>Gives n=4, the position of the string. </li></ul><ul><li>// search for a substring given string1 and string2 </li></ul><ul><li>if (string1.indexOf(string2,0) >=0) </li></ul><ul><li>result = string2 + “ exists in “ + string1; </li></ul><ul><li>else </li></ul><ul><li>result = string2 + “ does not exist in“ + string1; </li></ul>
  92. 92. Examining Strings 3 <ul><li>lastIndexOf: </li></ul><ul><li>As indexOf, but returns the position of the rightmost substring, if found. </li></ul><ul><li>endsWith:` </li></ul><ul><li>boolean r = “http”.endsWith(“p”); </li></ul><ul><li>// gives r = true </li></ul>
  93. 93. String Conversions <ul><li>Strings can be converted in to the other main types using the parse methods. </li></ul><ul><li>We can convert Strings to the primitive types using: Integer, Float, Double, Long, Boolean, Character. </li></ul><ul><li>These are special java classes called ‘wrapper classes’. They contain methods to handle the conversion. </li></ul><ul><li>int n = 123; </li></ul><ul><li>String s = Integer.toString(n); // gives s=“123” </li></ul><ul><li>int z = Integer.parseInt(s); // gives z =123 </li></ul>
  94. 94. Events <ul><li>Events allow us to develop user interfaces using buttons, sliders etc. </li></ul><ul><li>They are quite easy to use certainly less painful than in many other languages. </li></ul><ul><li>Event handling is carried out automatically in that the program continuously examines ‘events’ to see if they have occurred and then takes the appropriate action. </li></ul><ul><li>What we have to do is define the event we wish to use and ask Java to act as a ‘listener’ to detect when the event has occurred. </li></ul>
  95. 95. Input of Numbers From a Textfield <ul><li>Inputting integers via a textfield by: </li></ul><ul><li>int number = Integer.parseInt(textFieldName.getText()); </li></ul><ul><li>For real numbers the conversion of the string is a little more complicated: </li></ul><ul><li>Float temp = Float.valueOf(floatFieldName.getText()); </li></ul><ul><li>float value = temp.floatValue(); </li></ul><ul><li>Conversions can also be done with double numbers (Use Double). </li></ul>