La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe

Présentations similaires


Présentation au sujet: "LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe"— Transcription de la présentation:

1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe
LICENCE MIAGE Introduction Programmation Orientée Objet JAVA

2 P.O.O Langage Java Introduction (rappel) Bases du langage (rappel)
Programmation Orientée Objet

3 Organisation 8 cours 12 TDM Évaluation jeudi 10h-11h30
semaine 12 TDM groupe 1 (lundi 10h-12h) groupe 2 (lundi 13h-15h) semaine Évaluation Contrôle continu (amphi+TDM+partiel) (33%) Examen (67%) ECTS : 3

4 Bibliographie Java : de l'esprit à la méthode
Michel Bonjour et al. Vuibert The Java Programming Language Ken Arnold et James Gosling The Java Series. Addison Wesley consulter la Java Book List

5 Quelques sites Sun Gamelan
produits, documentation, the JavaTM Tutorial Java Developer Connection Gamelan JavaWorld Magazine Java FAQ

6 Créer votre première application
 Le premier programme, Hello, affiche simplement le texte "Hello !"  Créer un fichier source Hello.java Un fichier source contient du texte, écrit en Java Compiler le source en fichier bytecode Hello.class Le compilateur javac, traduit le texte source en instructions compréhensibles par la Machine Virtuelle Java (JVM) Exécuter le programme contenu dans le fichier bytecode L'interprète Java implémente la JVM L'interprète traduit le bytecode en instructions exécutables par votre machine

7 Compilation vs. Interprétation
Le compilateur convertit le programme source en programme exécutable avant exécution Programme source Compilateur Système d’exploitation Matériel Programme exécutable

8 Write once, run anywhere
La compilation d'un programme, ne génère pas d'instructions spécifiques à votre plate-forme Mais du bytecode Java, qui sont des instructions de la Machine Virtuelle Java (JVM) Si votre plate-forme (Windows, UNIX, MacOS, un browser Internet) dispose de VM, elle peut comprendre le bytecode

9

10 Application "Hello" Créer le fichier source Java Hello.java /**
* La classe Hello implémente une * application qui affiche "Hello !" sur la * sortie standard */ class Hello { public static void main(String[] args) { System.out.println("Hello !"); //Affiche le texte }

11 Compiler le fichier source javac Hello.java
Si la compilation réussit, le fichier Hello.class est créer. Ce fichier contient le bytecodes Interpréter et exécuter l'application java Hello L'argument de l'interprète est le nom de la classe à exécuter (pas le nom du fichier) Faire la distinction M/m

12 Environnement de développement
javac : le compilateur java java: la machine virtuelle java jdb: le debugger java jar: le système d’archivage java - utile pour les applets multifichiers javadoc: convertir le code en documentation HTML appletviewer: exécuter des applets sans passer par le navigateur

13 Disséquons l'application "Hello"
Insérer des commentaires Définir une classe Définir la méthode main Utiliser des classes et des objets

14 Insérer des commentaires
/** * Documentation * ignorer par le compilateur * générée par l'outil javadoc */ class Hello { public static void main(String[] args) { System.out.println("Hello !"); // commentaire sur une ligne /* commentaire … */ } The Java language supports three kinds of comments: /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the Java tool documentation . // text The compiler ignores everything from // to the end of the line.

15 Définir une classe /** * documentation */ class Hello { public static void main(String[] args) { System.out.println("Hello !"); // afficher le texte } une classe est la brique de base d'un langage orienté-objet ; elle fournit une description des données et des comportements associés A class--the basic building block of an object-oriented language such as Java--is a template that describes the data and behavior associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C.

16 Définir la méthode main
/** * documentation */ class Hello { public static void main(String[] args) { System.out.println("Hello !"); // afficher le texte } Une application Java doit contenir une méthode main Appelée en premier par l'interprète Qui appelle les autres méthodes nécessaires pour exécuter l'application A class--the basic building block of an object-oriented language such as Java--is a template that describes the data and behavior associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C.

17 Utiliser une méthode et une variable
class Hello { public static void main(String[] args) { System.out.println("Hello !"); } System.out.println("Hello !") La classe System (package java.lang) fournie des accès "system-independent" à des fonctionnalités "system-dependent" Variable out de la classe System Méthode println(…) A class--the basic building block of an object-oriented language such as Java--is a template that describes the data and behavior associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C.

18

19

20 Conventions d’écriture de code
Classe CompteEnBanque Méthodes crediterCompte(25) getSolde() setSolde(10) Variables empruntCourant Constantes TAUX_INTERET Java les respecte donc respectez-les !!

21 P.O.O Langage Java Introduction (rappel) Bases du langage (rappel)
Programmation Orientée Objet

22 Bases du Langage public class BasicsDemo {
public static void main(String[] args) { int sum = 0; for (int c = 1; c <= 10; c++){sum += c;} S.o.p("Sum = " + sum); } Que fait ce programme ? Même un petit programme comme celui-ci utilise de nombreuses caractéristiques du langages comme des variables, des opérateurs, et des instruction de flux de contrôle program that follows adds the numbers from 1 to 10 and displays the result The output from this program is: Sum = 55

23 Concept de Variable Définition : un élément d’information identifié par un nom On doit explicitement indiquer le nom et le type d’une variable On utilise le nom pour faire référence à l’information que la variable contient Le type détermine les valeurs licites pour la variable et les opérations autorisées Pour donner un nom et un type à une variable il faut la déclarer : type name Une variable, a une portée : la section de code ou le nom de la variable peut être utilisé

24 int maxInteger = Integer.MAX_VALUE;
float maxFloat = Float.MAX_VALUE; char aChar = 'S'; boolean aBoolean = true; S.o.p("Plus grand integer :" + maxInteger); S.o.p("Plus grand float :" + maxFloat); S.o.p("Le caractère est :" + aChar); S.o.p("Valeur du booléen :" + aBoolean); Plus grand integer : Plus grand float : e+38 Le caractère est : S Valeur du booléen : true

25

26

27 16-bit Unicode character
Keyword Description Size/Format (integers) byte Byte-length integer 8-bit two's complement short Short integer 16-bit two's complement int Integer 32-bit two's complement long Long integer 64-bit two's complement (real numbers) float Single-precision floating point 32-bit IEEE 754 double Double-precision floating point 64-bit IEEE 754 (other types) char A single character 16-bit Unicode character boolean A boolean value (true or false) true or false

28 Types élémentaires Primitive Data Types Integer Floating
byte 8bits to 127 float 32bits 1.4E E38 short 16bits to 32767 double 64bits 4.9E E308 int bits -2^31 to 2^31-1 long bits -2^63 to 2^63-1 Textual Logical char 16bits 0 to 65535 one bit : true or false

29 final int A_FINAL_VAR = 0;
Variable Final La valeur d’une variable déclarée final ne peut pas être modifiée après avoir été initialisée Une telle variable est similaire à une constante dans les autres langages de programmation Pour déclarer une variable final : final int A_FINAL_VAR = 0;

30 Opérateur Arithmétique
Operator Use Description + op1 + op2 Adds op1 and op2 - op1 - op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1%op2 Computes the remainder of dividing op1 by op2

31 Opérateur Relationnel
Operateur Use Returns true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal

32 Opérateur Conditionnel
Operator Use Returns true if && op1 && op2 op1 and op2 are both true conditionally evaluates op2 || op1 || op2 either op1 or op2 is true ! ! op op is false & op1 & op2 always evaluates op1 and op2 | op1 | op2 ^ op1 ^ op2 if op1 and op2 are different that is if one or the other of the operands is true but not both

33 Entrées au clavier : classe Console
Problème : les entrées au clavier ne sont pas aisées en Java Nous allons utilisé (Travaux Dirigés) la classe Console pour simplifier la tâche Console.readInt(str) retourne un nombre entier de type int entré au clavier Console.readDouble(str) retourne un nombre de type double entré au clavier

34 Utiliser la classe Console
Pour chaque classe qui fait appel à la classe Console ajoutez (entre votre commentaire de début et le mot class) import unsa.Console; ajouter comme dernière instruction de la méthode main() System.exit(0);

35 Classe Console Exemples
import unsa.Console; public class TestConsole{ public static void main (String args[]){ char c = Console.readChar("Entrez un char"); S.o.p("echo: " + c ); int i = Console.readInt("Entrez un int"); S.o.p("echo: " + i ); double d = Console.readDouble("Entrez un double"); S.o.p("echo: " + d ); long l = Console.readLong("Entrez un long"); S.o.p("echo: " + l ); System.exit(0); }

36 Contrôle du Flux d’instructions
Sans contrôle du flux les instructions sont exécutées dans l’ordre où elles apparaissent dans le fichier source Contrôler le flux pour Exécuter conditionnellement des instructions Exécuter de façon répétitive un bloc de code

37 Les Instructions de Contrôle
if return switch while continue do-while for break

38 while (expression) { instructions }
Instruction while On utilise l'instruction while pour exécuter répétitivement un bloc de code tant qu'une condition reste vraie while (expression) { instructions } On commence par évaluer l'expression, qui doit retourner une valeur booléenne Si expression retourne true, alors on exécute les instructions associées L'instruction while continue en testant expression et en exécutant les instructions jusqu'à ce que expression retourne false

39 Instruction while (2) Ce programme utilise une instruction while pour parcourir une string, copiant les caractères dans un buffer jusqu'à rencontrer la lettre 'g' String copyFromMe = "Copy this string until you encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i=0; char c=copyFromMe.charAt(i); while (c != 'g') { copyToMe.append(c); i=i+1; c = copyFromMe.charAt(i); } S.o.p(copyToMe); Valeur affichée par S.o.p ? The value printed by the last line is: Copy this strin

40 Instruction do-while Java fournit une autre structure similaire do-while do { instructions } while(expression); expression est évaluée à la base de la boucle les instructions associées sont donc exécutées au moins une fois

41 Instruction do-while (2)
String copyFromMe = "Copy this string until you encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i=0; char c ; do { c = copyFromMe.charAt(i); copyToMe.append(c); i=i+1 ; } while (c != 'g'); S.o.p(copyToMe); Valeur affichée par S.o.p ? The value printed by the last line is: Copy this strin

42 Instruction for for (initialisation ; terminaison ; incrément) { instructions } initialisation initialise la boucle ; exécuté une seule fois au début de la boucle terminaison détermine quand terminer la boucle evalué au début de chaque itération Quand l'expression retourne false, la boucle se termine incrément exécuté à la fin de chaque itération Souvent utilisé pour parcourir les éléments d'un tableau (array), ou les caractères d'une chaîne (string)

43 Instruction for int[] arrayOfInts = {32, 87, 3, 589};
for(int i=0; i<arrayOfInts.length; i++) { S.o.p(arrayOfInts[i] + " "); } Valeurs affichées par S.o.p ?

44 for vs. while for(int i=0 ; i<arrayOfInts.length ; i++) {
S.o.p(arrayOfInts[i] + " "); } int i=0 ; while(i<arrayOfInts.length) i++;

45 Garantir la fin des itérations
do { afficher(a) a = a+1; } while (a != 10) do { afficher(a) } while (a != 10) a = 1; do { afficher(a) a = a+1 ; } while (a != 10) a = 10; do { afficher(a) a = a+1; } while (a != 10)

46 Instructions if/else if (reponse == OK) { // code to perform OK action
} else { // code to perform Cancel action

47 Une cascade de if … int score = 76; char grade;
if (score >= 90) { grade = 'A'; } else // score < 90 if (score >= 80) { grade = 'B'; } else // score < 80 if (score >= 70) { grade = 'C'; } else // score < 70 if (score >= 60) { grade = 'D'; } else // score < 60 { grade = 'F'; } S.o.p("Grade = " + grade); Valeur affichée par S.o.p ? C

48 Instruction switch Permet d'exécuter, conditionnellement à la valeur d'un entier, certaines instructions int mois = 10; switch (mois) { case 1: S.o.p("Janvier") ; break; case 2: S.o.p("Février") ; break; case 3: S.o.p("Mars") ; break; case 10: S.o.p("Octobre") ; break; case 11: S.o.p("Novembre") ; break; case 12: S.o.p("Décembre") ; break; default: S.o.p("non valide!"); } Valeur affichée par S.o.p ?

49 Un exemple … Un programme qui permette de :
Saisir deux nombres réels au clavier Afficher un menu à l'écran S)omme des deux nombres P)roduit des deux nombres M)oyenne des deux nombres Saisir le choix de l'utilisateur, ‘S', 'P' ou 'M‘ Afficher le résultat correspondant

50 import unsa.Console; public class Test { public static void main(String [] args) { float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); char rep=Console.readChar("Faites votre choix"); switch (rep) { case 'S' : S.o.p(nb1+nb2);break; case ‘P' : S.o.p(nb1*nb2);break; case ‘M' : S.o.p((nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } System.exit(0);}}

51 import unsa.Console; public class Test { public static void main(String [] args) { float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); char rep=Console.readChar("Faites votre choix"); switch (rep) { case 'S' : case 's' : S.o.p(nb1+nb2);break; case 'p' : case 'P' : S.o.p(nb1*nb2);break; case 'm' : case 'M' : S.o.p((nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } System.exit(0);}}

52 public static void main(String [] args) {
char rep ; float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); do { rep=Character.toLowerCase(Console.readChar("choix ?")); switch (rep) { case ‘S': S.o.p("somme : "+(nb1+nb2)) ;break; case ‘P': S.o.p("produit: "+(nb1*nb2)) ;break; case ‘M': S.o.p("moyenne: "+(nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } } while ((rep != 's') && (rep != 'p') && (rep != 'm')) ;

53 Conversion d'un caractère minuscule en MAJUSCULE
Il faut distinguer le type primitif char et la classe Character char rep ; rep=Character.toLowerCase(Console.readChar("votre choix ?")); S.o.p(rep); Console.readChar("votre choix ?") readChar est une méthode de la classe Console qui retourne le char lu au clavier static char toLowerCase(char ch) Méthode static de la classe Character : le caractère donnée char ch est converti en minuscule avant d'être retourné en résultat char

54 Capitaliser un texte Public static void main(String[] args) {
String str=Console.readLine("Tapez un texte"); char ch; // un caractère de str char prevCh='.'; // le caractère précédent ch for (int i = 0; i < str.length(); i++ ) { ch = str.charAt(i); if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) ) S.o.p( Character.toUpperCase(ch) ); else S.o.p(ch); prevCh = ch; }

55 Calculer le PGCD de deux entiers A et B
Algorithme d'Euclide Calculer le PGCD de deux entiers A et B PGCD(A,B) = PGCD(B,R) A = (B x Q) + R 0 <= R < B 294 = (231 x 1) + 63 231 = (63 x 3) + 42 63 = (42 x 1) + 21 42 = (21 x 2) + 0 PGCD(294,231) = 21

56 Algorithme d'Euclide int a=21, b=14 ; int r ;
S.o.p("PGCD "+a+" et "+b); r=a%b; /* division euclidienne de a par b a=b*q+r et 0<=r<b */ while (r!=0){ a=b ; b=r; // pgcd(a,b)=pgcd(b,r) } S.o.p(b);

57 Le nombre Mystérieux public static void main (String args[]){
int inconnu = (int) (Math.random()*100); int score=0; int prop=Console.readInt("proposition :"); score++; while (prop != inconnu){ if (prop < inconnu) S.o.p("TROP PETIT"); else S.o.p("TROP GRAND"); prop=Console.readInt("proposition :"); score++; } S.o.p("Vous avez trouvé en "+score+" coups"); System.exit(0);

58 É s o p e r e s t e i c i e t s e r e p o s e
public static void main(String [] args) { final int taille ; String phrase=Console.readLine("Entrez une string"); taille = phrase.length(); int i = 0, j = taille - 1; while(i<taille/2 && phrase.charAt(i) == phrase.charAt(j)) {i++ ; j-- ;} if (I >= taille/2) S.o.p(phrase+" est un palindrome"); else S.o.p (phrase+" n’est pas un palindrome"); System.exit(0); }

59 É s o p e r e s t e i c i e t s e r e p o s e
public static void main(String [] args) { String phrase ; phrase=Console.readLine("votre texte").toUpperCase(); StringBuffer sb1 = new StringBuffer(phrase); StringBuffer sb2 = new StringBuffer(phrase); sb1.reverse(); if (sb1.toString().equals(sb2.toString())) S.o.p(phrase+" est un palindrome"); else S.o.p(phrase+" n'est pas un palindrome"); System.exit(0); }

60 Algorithme du drapeau tricolore
On aligne n boules, réparties en un nombre quelconque de boules bleues, blanches ou rouges, disposées dans un ordre quelconque Écrire un algorithme qui trie le tableau de telle façon que toutes les boules bleues apparaissent au début, suivies des boules blanches puis des boules rouges Le tri doit être réalisé en unique parcours

61

62 b r i b i r i r b i r

63 Algorithme du drapeau tricolore
int d[]={3,1,3,1,2,3,2,3,2,1}; // 1=bleu 2=blanc 3=rouge for(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");} int i=0 , b=0 , r=d.length-1 ; while ( i <= r ) { switch (d[i]) { case 1 : echanger(b,i); b++;i++;break; case 2 : i++; break; case 3 : echanger(r,i); r--; break; } S.o.p("le drapeau ..."); B = prochaine case vide pour un bleu R= prochaine case vide pour un rouge I indice courant de la boule examinée

64 Comment les arguments sont-ils passés aux méthodes ?
public class CallDemo { static void f(int b) { b = 10; } public static void main(String [] args) { int a = 5; f(a); S.o.p("a = " + a); Quelle est la valeur affichée, 5 ou 10 ? In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

65 Passage des arguments par valeur
public class CallDemo { static void f(int a) { a = 10; S.o.p("a de f= " + a); } public static void main(String args[]) { int a = 5; f(a); S.o.p("a du main = " + a); In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

66 Passage d'un objet en argument
static void lireTableau(int tl[]){ for (int i=0 ; i<tl.length ; i++) tl[i]=Console.readInt("Taper un entier : "); } static void afficherTableau(int ta[]){ for (int i=0;i<ta.length;i++) S.o.p(ta[i] + " "); public static void main(String [] args){ final int TAILLE=5; int tableau [] = new int[TAILLE]; lireTableau(tableau); afficherTableau(tableau); System.exit(0);

67 Sélectionner pour trier
public static void main(String [] args){ int [] tab = {-2, 0, 8 ,7 ,1, -5, 12, 10, 25, 5} ; final int TAILLE=tab.length ; int aux ; int indMin ; for(int k=0 ; k<TAILLE ; k++){ // rechercher la place IndMin du plus petit élément dans // le sous tableau tab[k..TAILLE] indMin=k ; for(int j=k+1 ; j<TAILLE ; j++) { if(tab[j] < tab[indMin]) indMin=j ;} // échanger l'élément d'indice indMin // avec l'élément d'indice k aux = tab[indMin]; tab[indMin] = tab[k]; tab[k] = aux; }

68 Sales tax in New York City is 8.25%
public static void main (String[] args) { final double TAUX = ; double prix=Double.valueOf(args[0]).doubleValue(); //double prix = Double.parseDouble(args[0]); S.o.p("taxe : " + prix*TAUX); S.o.p("prix ttc : " + prix*(1+TAUX)); } static Double valueOf(String s) Returns a new Double object initialized to the value represented by the specified String Double doubleValue()  Returns the double value of this Double static double parseDouble(String s) Returns a new double initialized to the value represented by the specified String

69

70 NEUTRE ARCHITECTURALEMENT
Le compilateur JAVA compile le code dans un langage fait d’instructions élémentaires, en fait, un code exécutable dans une machine virtuel (la «java virtual machine») Toutes les plates-formes, PC + windows, Mac, UNIX, digital contiennent la JVM. Ainsi que les navigateurs internet code.java Compilateur JAVA code.class JVM JVM JVM MAC Unix Windows


Télécharger ppt "LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe"

Présentations similaires


Annonces Google