Your SlideShare is downloading. ×
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
First postgrad java version 2
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

First postgrad java version 2

245

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
245
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

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

×