Cours 3. Tableaux Tableaux à 2 dimensions Tableaux d objets Classes String et StringBuffer Enumération POO 1

Documents pareils
Java Licence Professionnelle CISII,

Structure d un programme et Compilation Notions de classe et d objet Syntaxe

Package Java.util Classe générique

PROGRAMMATION PAR OBJETS

TD3: tableaux avancées, première classe et chaînes

Utilisation d objets : String et ArrayList

Une introduction à Java

Java Licence Professionnelle CISII, Cours 2 : Classes et Objets

Cours 1: Java et les objets

Programme Compte bancaire (code)

1. Structure d un programme C. 2. Commentaire: /*..texte */ On utilise aussi le commentaire du C++ qui est valable pour C: 3.

Programmation par les Objets en Java

Corrigé des exercices sur les références

as Architecture des Systèmes d Information

Généralités sur le Langage Java et éléments syntaxiques.

Plan du cours. Historique du langage Nouveautés de Java 7

Flux de données Lecture/Ecriture Fichiers

Cours intensif Java. 1er cours: de C à Java. Enrica DUCHI LIAFA, Paris 7. Septembre Enrica.Duchi@liafa.jussieu.fr

Introduction à Java. Matthieu Herrb CNRS-LAAS. Mars

Chapitre 10. Les interfaces Comparable et Comparator 1

Programmer en JAVA. par Tama

Projet de programmation (IK3) : TP n 1 Correction

Info0101 Intro. à l'algorithmique et à la programmation. Cours 3. Le langage Java

Java Licence Professionnelle Cours 7 : Classes et méthodes abstraites

Polycopié Cours Programmation Orientée Objet sous Java Programme : Filière SMI S5

Exceptions. 1 Entrées/sorties. Objectif. Manipuler les exceptions ;

Premiers Pas en Programmation Objet : les Classes et les Objets

Tp 1 correction. Structures de données (IF2)

Prendre le marteau, le tableau, le mètre, le crayon, la ficelle, le clou, la pointe ;

INF 321 : mémento de la syntaxe de Java

INTRODUCTION A JAVA. Fichier en langage machine Exécutable

Licence Bio Informatique Année Premiers pas. Exercice 1 Hello World parce qu il faut bien commencer par quelque chose...

Langage Java. Classe de première SI

ALGORITHMIQUE ET PROGRAMMATION ORIENTEE OBJET

OpenPaaS Le réseau social d'entreprise

Exercices sur les interfaces

TP, première séquence d exercices.

TP n 2 Concepts de la programmation Objets Master 1 mention IL, semestre 2 Le type Abstrait Pile

Programmation Objet I

Langage et Concepts de ProgrammationOrientée-Objet 1 / 40

Programmation Orientée Objet application au langage Java Version Novembre 2007

Programmation avec des objets : Cours 7. Menu du jour

JAVA TD0. Prise en main du langage Environnement de base JAVA 1

Langage à objets : JAVA (1)

LMI 2. Programmation Orientée Objet POO - Cours 9. Said Jabbour. jabbour@cril.univ-artois.fr

Le prototype de la fonction main()

Auto-évaluation Programmation en Java

Programmation en Java IUT GEII (MC-II1) 1

Cours 1 : Introduction. Langages objets. but du module. contrôle des connaissances. Pourquoi Java? présentation du module. Présentation de Java

Aide mémoire UML & Java 1ère partie : Introduction. marc.lemaire@u-cergy.fr

Java c est quoi? Java pourquoi?

Cours de C++ François Laroussinie. 2 novembre Dept. d Informatique, ENS de Cachan

Support de cours et TD Programmation Orientée Objet

Programmation Réseau. Sécurité Java. UFR Informatique jeudi 4 avril 13

Synchro et Threads Java TM

Corrigés des premiers exercices sur les classes

Création d objet imbriqué sous PowerShell.

Derrière toi Une machine virtuelle!

Programmation Orientée Objet - Licence TIS CM8/9. Rappel sur la séance précédente. Lancelot Pecquet Lancelot.Pecquet@math.univ-poitiers.

Classe Interne, Anonyme & Enumération

TP1 : Initiation à Java et Eclipse

Introduction au langage Java

ACTIVITÉ DE PROGRAMMATION

COMPARAISONDESLANGAGESC, C++, JAVA ET

Langage et Concepts de Programmation Objet. 1 Attributs et Méthodes d instance ou de classe. Travaux Dirigés no2

Dis papa, c est quoi un bus logiciel réparti?

TD/TP PAC - Programmation n 3

1. Langage de programmation Java

Cours d initiation à la programmation en C++ Johann Cuenin

Le Langage C Version 1.2 c 2002 Florence HENRY Observatoire de Paris Université de Versailles florence.henry@obspm.fr

Gestion distribuée (par sockets) de banque en Java

Cours d Algorithmique-Programmation 2 e partie (IAP2): programmation 24 octobre 2007impérative 1 / 44 et. structures de données simples

RAPPELS SUR LES METHODES HERITEES DE LA CLASSE RACINE Object ET LEUR SPECIALISATION (i.e. REDEFINITION)

TD/TP PAC - Programmation n 3

RMI le langage Java XII-1 JMF

P r ob lé m a t iq u e d e la g é n é r icit é. Pr in cip e d e la g é n é r icit é e n Ja v a ( 1 /3 )

Programmation Orientée Objets Le Langage JAVA

INITIATION AU LANGAGE JAVA

TP3. Mail. Attention aux fausses manoeuvres lors de ce TP vous pouvez endommager votre mail sur ouindose.

Page 1 sur 5 TP3. Thèmes du TP : l la classe Object. l Vector<T> l tutorial Interfaces. l Stack<T>

Bases du langage. Historique Applications et applets Éléments de base du langage Classes et objets Les exceptions

TP Programmation Java / JDBC / Oracle

Les chaînes de caractères

Encapsulation. L'encapsulation consiste à rendre les membres d'un objet plus ou moins visibles pour les autres objets.

Quelques patterns pour la persistance des objets avec DAO DAO. Principe de base. Utilité des DTOs. Le modèle de conception DTO (Data Transfer Object)

Java Licence Professionnelle CISII,

Conventions d écriture et outils de mise au point

Principes des langages de programmation INF 321. Eric Goubault

Programmation Par Objets

Un ordonnanceur stupide

Prendre le marteau, le tableau, le mètre, le crayon, la ficelle, le clou, la pointe ;

Programmation Objet II

Claude Delannoy. 3 e édition C++

4. Groupement d objets

Informatique / Programmation

Initiation à JAVA et à la programmation objet.

Programmation système de commandes en C

Notions fondamentales du langage C# Version 1.0

Programmation Orientée Objet Java

Chap III : Les tableaux

Transcription:

Cours 3 Tableaux Tableaux à 2 dimensions Tableaux d objets Classes String et StringBuffer Enumération POO 1

Les tableaux ne sont pas ni des objets ni des types primitifs. Un tableau se rapproche d un objet Il est manipulé par référence (adresse) Il nécessite de new pour être défini Déclaration char tableau[] ou char[] tableau Création En utilisant new int tab[]; tab=new int[5]; char t2[]= new char[4]; implicitement avec l initialisation int t2[]={1,2,3; POO 2

La taille est fixée On peut accéder à la taille par le champ length Les indices entre 0 et length-1 Dépassement d indice : lancement d exception ArrayIndexOutOfBoundsException Un objet ou un tableau qui n est plus référencé est récupéré par ramasse-miettes (garbage) POO 3

public class TabAffec {public static void main(string args[]) {char t1[]={'b','o','n','j','o','u','r'; char t2[]={'h','e','l','l','o'; char t3[]={'x','x','x','x'; t3=t1; t1=t2; t2=t3; System.out.print("t1 ="); for (int i=0;i<t1.length;i++) System.out.print (t1[i]); System.out.println(); System.out.print("t2 ="); for (int i=0;i<t2.length;i++) System.out.print (t2[i]); System.out.println(); System.out.print("t3 ="); for (int i=0;i<t3.length;i++) System.out.print (t3[i]); System.out.println(); t1=hello t2=bonjour t3=bonjour POO 4

Les paramètres du programme class Prog23 { public static void main (String args[]) {int i; System.out.println("les arguments :"); for (i=0; i<args.length ; ++i) System.out.println(args[i]); Exécution java Prog23 "Bonjour coucou " a b les arguments : Bonjour coucou a b POO 5

class UtilTab {static double somme(double[] t) {double s=0; int i; for (i=0;i <t.length; i++) s+=t[i]; return s; static void affiche (double[] t) {for (int i=0; i <t.length; i++) System.out.print(t[i]+" "); System.out.println(); public static double[] somme (double[] t1, double[] t2) { int n=t1.length; if (n!=t2.length) return null; double [] res= new double[n]; for (int i=0; i <n; i++) res[i]=t1[i]+t2[i]; return res; public class TstUtil { public static void main(string[] args) { double tab1[]={1.5, 2.25, 3.5, 4.0; System.out.println("tab1 "); UtilTab.affiche(tab1); System.out.println("somme" + UtilTab.somme(tab1)); double tab2[]={2.5, 1.5, 3.5, 4.5; System.out.println("tab2 "); UtilTab.affiche(tab2); double [] tab3= UtilTab.somme(tab1,tab2); System.out.println("tab1+tab2 ");UtilTab.affiche(tab3); POO 6

Tableaux à deux dimensions int [][] tab; la référence tab qui pointe sur null tab=new int [2][3]; un tableau de taille 2 de tableaux d entiers de taille 3 initialisés par défaut à 0 tableau[1][1]=5; tableau[0]=new int[2]; POO 7

import java.io.*; import java.util.scanner; class Matrice{ int[][] tab; int nb_ligne, nb_col; public Matrice() { int i,j;scanner keyboard =new Scanner(System.in); nb_ligne=keyboard.nextint();nb_col=keyboard.nextint(); tab=new int[nb_ligne][nb_col]; for (i=0;i<nb_ligne;i++) {for(j=0;j<nb_col;j++) tab[i][j]=keyboard.nextint(); public void affiche() {int i,j;for (i=0;i<nb_ligne;i++) {for (j=0;j<nb_col;j++) System.out.print(tab[i][j]+" "); System.out.println(" "); POO 8

class TableauB {public static void main(string[] argv) {boolean[] tableau={true,false,true; System.out.println("Deuxieme element de tableau : "+ tableau[1]); /*A l'execution, on obtient : Deuxieme element de tableau : false */ POO 9

Tableaux d objets class Point {private int x,y; public Point(int a, int b) {x=a; y=b; public int getx() {return x; public int gety() {return y; public void affiche() {System.out.println("x = "+x+" y = "+y); class Gestion_tab { private Point[] tab; private int nb_pts_positifs; public Gestion_tab( int n) {tab=new Point[n]; public void ajout_pts() {for (int i=0; i <tab.length;i++) tab[i]=new Point(); POO 10

public void calcul_pts_positifs() {int nb=0, i; for (i=0;i < tab.length;i++) if ((tab[i].getx() >0) &&(tab[i].gety()>0)) nb++; nb_pts_positifs=nb; public void affiche() {for (int i=0; i <tab.length;i++) tab[i].affiche(); public class TestGestion { public static void main (String[] args) {Gestion_tab t=new Gestion_tab(3); t.ajout_pts(); t.affiche(); t.calcul_pts_positifs(); POO 11

FOR EACH double[] a=new double[3]; for (int i = 0; i < a.length; i++) a[i] = 0.0; équivalent à for (double element : a) element = 0.0; for (TypedeBaseTableau NomVariable : NomTableau) {instructions Méthodes avec un nombre variable d arguments int... a Type... ArrayName les arguments sont placés dans un tableau POO 12

public class UtilityClass { /** Returns the largest of any number of int values. */ public static int max(int... arg) { if (arg.length == 0) { System.out.println("Fatal Error: maximum of zero values."); System.exit(0); int largest = arg[0]; for (int i = 1; i < arg.length; i++) if (arg[i] > largest) largest = arg[i]; return largest; POO 13

Classe String Définie dans le paquetage java.lang String blessing = "Live long and prosper."; Méthodes public int length(); public int compareto(string s); >0 si la chaîne est après s (ordre lexicographique) <0 si elle est avant s =0 si égale int l= "bonjour ".length(); String s= "abc" ; String s1= "dbc" ; if (s.compareto(s1) <0) POO 14

Concatenation: + String greeting ="Hello ; String javaclass ="class ; greeting + javaclass est "Hello class" concatenation de String avec un autre type est un String "The answer is " + 42 est "The answer is 42" POO 15

Classe StringBuffer Les chaînes modifiables charat(int i) retourne le ième char (classe String a aussi cette méthode) setcharat(int i, char c) remplace le ième char par c POO 16

POO 17 1-17 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 18 1-18 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 19 Copyright 2008 Pearson Addison-Wesley. All rights reserved 1-19

POO 20 1-20 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 21 1-21 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 22 1-22 Copyright 2008 Pearson Addison-Wesley. All rights reserved

Méthode tostring public String tostring() retourne la chaîne de caractères pour les données dʼun objet Point a=new Point(1,3); System.out.println(a);affichera Point@2ac982 si la méthode tostring est définie comme suit dans la classe Point: public String tostring() {return("x= "+x+ " y= "+y); System.out.println(a.toString); affichera x= 1 y= 3 System.out.println(a); affichera x= 1 y= 3 POO 23

ENUMERATIONS Définis avant les méthodes (avec les constantes) enum TypeName {VALUE_1, VALUE_2,, VALUE_N; majuscules (constantes) enum WorkDay {MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY Déclaration des variables WorkDay meetingday, availableday; Affectation des valeurs meetingday = WorkDay.THURSDAY; availableday = null; WorkDay meetingday = WorkDay.THURSDAY; POO 24

Affichage System.out.println(meetingDay); résultat: THURSDAY comme System.out.println(WorkDay.THURSDAY); égalité avec (==) ou (equals) if (meetingday == availableday) System.out.println( reunion aura lieu."); if (meetingday == WorkDay.THURSDAY) System.out.println("weekend prolonge!); POO 25

POO 26 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 27 Copyright 2008 Pearson Addison-Wesley. All rights reserved

POO 28 Copyright 2008 Pearson Addison-Wesley. All rights reserved

Copyright 2008 Pearson Addison-Wesley. All rights reserved Copyright POO 2008 Pearson Addison-Wesley. All rights reserved 29

import java.util.scanner; public class EnumSwitchDemo { enum Flavor {VANILLA, CHOCOLATE, STRAWBERRY; public static void main(string[] args) { Flavor favorite = null; Scanner keyboard = new Scanner(System.in); System.out.println("What is your favorite flavor?"); String answer = keyboard.next(); answer = answer.touppercase(); favorite = Flavor.valueOf(answer); switch (favorite) {case VANILLA: System.out.println("Classic"); break; case CHOCOLATE: System.out.println("Rich"); break; default: System.out.println("I suppose you said STRAWBERRY."); break; POO 30