70
1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA [email protected] http://deptinfo.unice.fr/~pc

1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA [email protected] pc

Embed Size (px)

Citation preview

Page 1: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

1

LICENCE MIAGE

IntroductionProgrammation Orientée Objet

JAVA

[email protected]://deptinfo.unice.fr/~pc

Page 2: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

2

P.O.OLangage Java

1) Introduction (rappel)

2) Bases du langage (rappel)

3) Programmation Orientée Objet

Page 3: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

3

Organisation

• 8 cours– jeudi 10h-11h30– semaine 40 - 42..45 - 47..49

• 12 TDM – groupe 1 (lundi 10h-12h)– groupe 2 (lundi 13h-15h)– semaine 41..44 - 46..51 - 1 - 2

• Évaluation– Contrôle continu (amphi+TDM+partiel) (33%)– Examen (67%)– ECTS : 3

Page 4: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

4

Java : de l'esprit à la méthodeMichel Bonjour et al. Vuibert

The Java Programming LanguageKen Arnold et James GoslingThe Java Series. Addison Wesley

consulter la Java Book List http://metalab.unc.edu/javafaq/books.html

Bibliographie

Page 5: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

5

Quelques sites

Sun

http://java.sun.com

produits, documentation, the JavaTM Tutorial

Java Developer Connection

Gamelan

http://www.gamelan.com

JavaWorld Magazine

http://www.javaworld.com/

Java FAQ

http://www.ibiblio.org/javafaq/javafaq.html

Page 6: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

6

Créer votre première application

 Le premier programme, Hello, affiche simplement le texte "Hello !" 

1. Créer un fichier source Hello.javaUn fichier source contient du texte, écrit en Java 

2. Compiler le source en fichier bytecode Hello.classLe compilateur javac, traduit le texte source en instructions

compréhensibles par la Machine Virtuelle Java (JVM) 

3. Exécuter le programme contenu dans le fichier bytecodeL'interprète Java implémente la JVML'interprète traduit le bytecode en instructions exécutables par votre

machine

Page 7: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

7

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

Compilation vs. Interprétation

Page 8: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 9: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

9

Page 10: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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}

}

Page 11: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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'applicationjava 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

Page 12: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 13: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 14: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 … */

}}

Page 15: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 16: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 17: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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"

System.out.println("Hello !")Variable out de la classe System

System.out.println("Hello !")Méthode println(…)

http://java.sun.com/j2se/1.4.2/docs/api/index.html

Page 18: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

18

Page 19: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

19

Page 20: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 21: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

21

P.O.OLangage Java

1) Introduction (rappel)

2) Bases du langage (rappel)

3) Programmation Orientée Objet

Page 22: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 23: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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é

Page 24: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 : 2 147 483 647Plus grand float : 3.40282e+38Le caractère est : SValeur du booléen : true

Page 25: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

25

Page 26: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

26

Page 27: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

27

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 character16-bit Unicode character

boolean A boolean value(true or false) true or false

Page 28: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

28

Types élémentaires

byte 8bits -128 to 127

short 16bits -32768 to 32767

int 32bits -2^31 to 2^31-1

long 64 bits -2^63 to 2^63-1

Integer

float 32bits 1.4E-45 3.4E38

double 64bits 4.9E-324 1.8E308

Floating

char 16bits 0 to 65535

Textual

one bit : true or false

Logical

Primitive Data Types

Page 29: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

29

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;

Page 30: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 31: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 32: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

32

Opérateur Conditionnel

Operator Use Returns true if

&& op1 && op2 op1 and op2 are both trueconditionally evaluates op2

|| op1 || op2 either op1 or op2 is trueconditionally evaluates op2

! ! op op is false

& op1 & op2 op1 and op2 are both truealways evaluates op1 and op2

| op1 | op2 either op1 or op2 is truealways evaluates op1 and op2

^ op1 ^ op2 if op1 and op2 are different

that is if one or the other of the operands is true but not both

Page 33: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 34: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 35: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

35

Classe ConsoleExemples

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

}}

Page 36: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 37: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

37

Les Instructions de Contrôle

if

switch

for

while do-while

break

continue

return

Les Instructions de Contrôle

Page 38: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

38

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

Page 39: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 40: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

40

Instruction do-while

Java fournit une autre structure similaire do-whiledo {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

Page 41: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 42: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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)

Page 43: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 44: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

44

for vs. while

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

}

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

}

Page 45: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

45

do {afficher(a)a = a+1;}

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)

do {

afficher(a)

}

while (a != 10)

Garantir la fin des itérations

Page 46: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

46

Instructions if/else

if (reponse == OK) { // code to perform OK action

}

if (reponse == OK) {// code to perform OK action

}else {// code to perform Cancel action

}

Page 47: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 48: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 49: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

49

Un exemple …

Un programme qui permette de :

Saisir deux nombres réels au clavier Afficher un menu à l'écran

S)omme des deux nombresP)roduit des deux nombresM)oyenne des deux nombres

Saisir le choix de l'utilisateur, ‘S', 'P' ou 'M‘ Afficher le résultat correspondant

Page 50: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 *");

S.o.p("*****************************");

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

Page 51: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 *"); S.o.p("*****************************"); 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);}}

Page 52: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 *");

S.o.p("*****************************");

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

}

Page 53: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

53

Conversion d'un caractèreminuscule en MAJUSCULE

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

Il faut distinguer le type primitif char et la classe Character

Page 54: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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;

}

}

Page 55: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

55

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

Algorithme d'Euclide

Page 56: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

56

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)r=a%b;

}S.o.p(b);

Algorithme d'Euclide

Page 57: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

}

Page 58: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

58

É s o p e r e s t er e s t e i c i e te 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);}

Page 59: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

59

É s o p e r e s t er e s t e i c i e te 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);

}

Page 60: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

60

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

Algorithme du drapeau tricolore

Page 61: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

61

Page 62: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

62

b ri

b i r

b i r

i r

Page 63: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

63

int d[]={3,1,3,1,2,3,2,3,2,1};// 1=bleu 2=blanc 3=rougefor(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 ..."); for(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");}

Algorithme du drapeau tricolore

Page 64: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 ?

Page 65: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

Page 66: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

}

Page 67: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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 kaux = tab[indMin];tab[indMin] = tab[k];tab[k] = aux;

}}

Page 68: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

68

Sales tax in New York City is 8.25%

public static void main (String[] args) {final double TAUX = 0.0825 ;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

Page 69: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

69

Page 70: 1 LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe.collard@unice.fr pc

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

JVMJVM

JVM

code.java

code.class

Compilateur JAVA

MACWindows

Unix