Introduction à Java Corrections des exercices
Transcription
Introduction à Java Corrections des exercices
Introduction à Java Exercice 7 Code String s = "12.34"; double a = Double.parseDouble(s); System.out.println ("La chaine \"" + s + "\" vaut : " + a); Corrections des exercices Exercice 1 Résultat La chaine "12.34" vaut : 12.34 Soit l’entité « caissier » Définir - son identité : nom, prénom, code badge - son état : caisse numéro 3, horaire 2, etc. - son comportement : ouvrir caisse, typer article, encaisser, etc. Exercice 8 Code Double aDouble = new Double System.out.println ("Valeur System.out.println ("Valeur System.out.println ("Valeur Exercice 2 Dernière version du SDK : J2SE 1.4.2 http://java.sun.com/j2se/1.4.2/download.html (3.141592); : " + aDouble.doubleValue()); max : " + aDouble.MAX_VALUE); min : " + aDouble.MIN_VALUE); Résultat Valeur : 3.141592 Valeur max : 1.7976931348623157E308 Valeur min : 4.9E-324 Exercice 3 classe java.lang.String méthode public String toLowerCase( ) http://java.sun.com/j2se/1.4.2/docs/api/index.html Exercice 9 Exercice 4 Code String s = "Bonjour"; String t = ""; for (int i = s.length()-1; i >= 0; i--) t += s.charAt(i); System.out.println ("Chaine initiale : " + s); System.out.println ("Chaine obtenue : " + t); Taper dans une invite de commandes l’instruction java -version Exercice 5 Le plugin 1.4.2 est disponible pour les navigateurs. Exercice 6 Code public class Bienvenue { public static void main(String args[]) { System.out.println ("Bienvenue dans le monde Java"); } } Résultat Chaine initiale : Bonjour Chaine obtenue : ruojnoB Instructions de lancement javac Bienvenue.java java Bienvenue Résultat Bienvenue dans le monde Java ©Laura Perret 1 / 31 05.11.2006 ©Laura Perret 2 / 31 05.11.2006 Exercice 12 Exercice 10 Code String s = "elu par cette crapule"; int i = 0, compteur = 0; while (i != -1) { i = s.indexOf(' ', i+1); compteur++; } System.out.println ("La chaine \"" + s + "\" contient " + compteur + " mots."); Résultat La chaine "elu par cette crapule" contient 4 mots. Code String texte = "To be or not to be."; String motif = "to"; int compteur = 0; Pattern pattern = Pattern.compile(motif); Matcher matcher = pattern.matcher(texte.toLowerCase()); while (matcher.find()) { compteur++; } System.out.println ("La chaine \"" + texte + "\" contient " + compteur + " fois le motif \"" + motif + "\"."); Exercice 11 Code String s = "elu par cette crapule"; //String s = "coucou"; int i = 0, j = s.length()-1; boolean palindrome = true, done = false; Résultat La chaine "To be or not to be." contient 2 fois le motif "to". Exercice 13 Code String texte = "To be or not to be."; String motif = "be"; String rempl = "think"; Pattern pattern = Pattern.compile(motif); Matcher matcher = pattern.matcher(texte.toLowerCase()); while (i < j && !done) { while (s.charAt(i) == ' ') i++; while (s.charAt(j) == ' ') j--; if (s.charAt(i++) != s.charAt(j--)) { palindrome = false; done = true; } String resultat = matcher.replaceAll(rempl); } if (palindrome) System.out.println ("La chaine \"" + s + "\" est un palindrome"); else System.out.println ("La chaine \"" + s + "\" n'est pas un palindrome"); System.out.println ("Chaine originale : \"" + texte + "\""); System.out.println ("Chaine obtenue : \"" + resultat + "\""); Résultat Chaine originale : "To be or not to be." Chaine obtenue: "to think or not to think." Résultat La chaine "elu par cette crapule" est un palindrome ©Laura Perret 3 / 31 05.11.2006 ©Laura Perret 4 / 31 05.11.2006 Exercice 14 System.out.println ("\nMatrice 2\n"); Code for (int i = 0; i < 3; i++) { int[] tableau = new int[10]; for (int j = 0; j < 3; j++) tableau[0] = 1; tableau[1] = 1; System.out.println (); System.out.print(matrice2[i][j] + " "); } for (int i = 0; i < 3; i++) { // ligne de m1 for (int i = 2; i < tableau.length; i++) tableau[i] = tableau[i-2] + tableau[i-1]; System.out.println ("Suite de Fibonacci\n"); for (int i = 0; i < tableau.length; i++) System.out.print (tableau[i] + " "); System.out.println (); for (int j = 0; j < 3; j++) { // colonne de m2 for (int k = 0; k < 3; k++) { // element variable produit = matrice1[i][k] * matrice2[k][j]; somme += produit; } Résultat Suite de Fibonacci 1 1 2 3 5 8 13 21 34 55 matrice3[i][j] = somme; somme = 0; Exercice 15 } Code } int[][] matrice1 = new int[3][3]; System.out.println ("\nMatrice 3\n"); int[][] matrice2 = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) int[][] matrice3 = new int[3][3]; int compteur = 0; System.out.print(matrice3[i][j] + " "); int somme = 0, produit = 0; System.out.println (); } for (int i = 0; i < 3; i++) Résultat Matrice 1 0 1 2 3 4 5 6 7 8 Matrice 2 9 8 7 6 5 4 3 2 1 Matrice 3 12 9 6 66 54 42 120 99 78 for (int j = 0; j < 3; j++) matrice1[i][j] = compteur++; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) matrice2[i][j] = compteur--; System.out.println ("Matrice 1\n"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print(matrice1[i][j] + " "); System.out.println (); } ©Laura Perret 5 / 31 05.11.2006 ©Laura Perret 6 / 31 05.11.2006 Exercice 16 Code double d = 3.141592; int i = (int) d; short s = 65; char c = (char) s; System.out.println ("Double : " + d + "\nEntier : " + i); System.out.println ("Short : " + s + "\nCaractere : " + c); Résultat Double : 3.141592 Entier : 3 Short : 65 Caractere : A Résultat 6 + 3 * 4 / 2 + 2 = 14 a = 2; a++ = 2 12-- ne passe pas la compilation b = 3; --b = 2 a+=b+=5 = 10 (a=8) < 10 ? a++ : --a = 8 a = 2; b = 3; b+++a = 5 a = 2 b = 4 Exercice 18 Code int i = (int) (Math.random() * 10); if (i % 2 == 0) System.out.println ("Le nombre " + i + " est pair."); else System.out.println ("Le nombre " + i + " est impair."); Exercice 17 Code System.out.println ("6 + 3 * 4 / 2 + 2 = " + (6 + 3 * 4 / 2 + 2)); int a = 2; System.out.println ("a = 2; a++ = " + (a++)); Résultat Le nombre 2 est pair. //System.out.println ("12-- = " + 12--); System.out.println ("12-- ne passe pas la compilation"); int b = 3; System.out.println ("b = 3; --b = " + (--b)); a = 3; b = 2; System.out.println ("a+=b+=5 = " + (a+=b+=5)); System.out.println ("(a=8) < 10 ? a++ : --a = " + ((a=8) < 10 ? a++ : --a)); a = 2; b = 3; System.out.println ("a = 2; b = 3; b+++a = " + (b+++a)); System.out.println ("a = " + a + "\nb = " + b); ©Laura Perret 7 / 31 05.11.2006 ©Laura Perret 8 / 31 05.11.2006 Exercice 19 Code int note = (int) (Math.random() * 6); switch (note) { case 0 : case 1 : case 2 : case 3 : System.out.println ("note " + note + " : insuffisant"); break; case 4 : System.out.println ("note " + note + " : suffisant"); break; case 5 : System.out.println ("note " + note + " : bien"); break; case 6 : System.out.println ("note " + note + " :tres bien"); break; } Résultat note 3 : insuffisant Code int n = (int) (Math.random() * 10); Code int i = 0, j = 1; while (j>0) { i++; j = i * i; } System.out.println("Le plus grand carre entier : " + (i-1) + "^2 = " + ((i-1) * (i-1))); Exercice 22 System.out.println ("Table de multiplication de " + n + "\n"); for (int i = 0; i <= 12; i++) System.out.println (i + " * " + n + " = " + (i*n)); 9 / 31 Exercice 21 Résultat Le plus grand carre entier : 46340^2 = 2147395600 Exercice 20 ©Laura Perret Résultat Table de multiplication de 9 0 * 9 = 0 1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81 10 * 9 = 90 11 * 9 = 99 12 * 9 = 108 05.11.2006 Code String username, password; InputStreamReader flux = new InputStreamReader (System.in); BufferedReader in = new BufferedReader (flux); try { do { System.out.println ("Veuillez saisir votre username et password.\n"); System.out.print ("username : " ); username = in.readLine(); System.out.print ("password : " ); password = in.readLine(); ©Laura Perret 10 / 31 05.11.2006 if (!(username.equals("Pierre") && password.equals("titi"))) System.out.print ("\nLogin incorrect. "); } while (!(username.equals("Pierre") && password.equals("titi"))); Exercice 24 System.out.println ("\nLogin correct. Bienvenue Pierre."); Code Date.java public class Date { private int jour; private int mois; private int annee; } catch (IOException e) { System.out.println (e); } Résultat Veuillez saisir votre username et password. username : Pierre password : titi Login correct. Bienvenue Pierre. public Date () { jour = 1; mois = 1; annee = 1980; } Exercice 23 Code int num, denom; InputStreamReader flux = new InputStreamReader (System.in); BufferedReader in = new BufferedReader (flux); try { System.out.print ("numerateur : "); num = Integer.parseInt(in.readLine()); System.out.print ("denominateur : "); denom = Integer.parseInt(in.readLine()); System.out.println (num + " / " + denom + " = " + (num/denom)); } catch (IOException e) { System.out.println (e); } 11 / 31 public Date (int j, int m, int a) { jour = j; mois = m; annee = a; } public int getJour () { return jour; } assert (denom != 0) : "Denominateur null, division par 0 non autorisee."; ©Laura Perret Résultat numerateur : 12 denominateur : 0 Exception in thread "main" java.lang.AssertionError: Denominateur null, division par 0 non autorisee.at TrivialApplication.exercice17(TrivialApplication.java) public int getMois () { return mois; } public int getAnnee () { return annee; } public String toString () { return new String (jour + "/" + mois + "/" + annee); } 05.11.2006 ©Laura Perret 12 / 31 05.11.2006 public boolean equals (Object o) { Personne p = (Personne) o; return nom.equals(p.nom) && prenom.equals(p.prenom) && naissance.equals(p.naissance); } public boolean equals (Object o) { Date d = (Date) o; return d.jour == jour && d.mois == mois && d.annee == annee; } } Code Personne.java public class Personne { protected static int instances = 0; protected String nom; protected String prenom; protected Date naissance; public String getNom () { return nom; } public String getPrenom () { return prenom; } public Date getNaissance () { return naissance; } public Personne () { nom = "Dupont"; prenom = "Pierre"; naissance = new Date (); instances++; } protected void finalize () throws Throwable { super.finalize(); instances--; System.out.println ("Bye bye ..."); } public Personne (String n, String p, Date d) { nom = n; prenom = p; naissance = d; instances++; } } Code de test Date d = new Date (12, 4, 1970); Personne p1 = new Personne (); System.out.println (p1); Personne p2 = new Personne ("Muller", "Jacques", d); public static int getInstances () { return instances; } System.out.println (p2); public String toString () { return new String ( "\nNom : " + nom + "\nPrenom : " + prenom + "\nDate de naisssance : " + naissance.toString()); } ©Laura Perret 13 / 31 05.11.2006 Résultat Nom : Dupont Prenom : Pierre Date de naisssance : 1/1/1980 Nom : Muller Prenom : Jacques Date de naisssance : 12/4/1970 ©Laura Perret 14 / 31 05.11.2006 Exercice 25 Exercice 26 Code Vector v = new Vector (); Personne p; Code de test public class Employe extends Personne { protected String departement; protected String fonction; protected int salaire; p = new Personne (); v.add(p); public Employe () { super (); departement = "Ventes"; fonction = "vendeur"; salaire = 60000; } p = new Personne ("Muller", "Jacques", new Date (12, 6, 1972)); v.add(p); p = new Personne ("Perret", "Daniel", new Date (22, 7, 1968)); v.add(p); public Employe (String n, String p, Date d, String dep, String f, int s) { super (n, p, d); departement = dep; fonction = f; salaire = s; } for (int i = 0; i < v.size(); i++) System.out.println ((Personne) v.elementAt(i)); Résultat Nom : Dupont Prenom : Pierre Date de naisssance : 1/1/1980 public String getDepartement () { return departement; } Nom : Muller Prenom : Jacques Date de naisssance : 12/6/1972 public String getFonction () { return fonction; } Nom : Perret Prenom : Daniel Date de naisssance : 22/7/1968 public int getSalaire () { return salaire; } public String toString () { return new String (super.toString() + "\nDepartement : " + departement + "\nFonction : " + fonction + "\nSalaire : SFr. " + salaire + ".-"); } ©Laura Perret 15 / 31 05.11.2006 ©Laura Perret 16 / 31 05.11.2006 Exercice 27 public boolean equals (Object o) { Employe e = (Employe) o; return super.equals(e) && departement.equals(e.departement) && fonction.equals(e.fonction) && salaire == e.salaire; } Code Association.java public abstract class Association { protected Object clef; protected Object valeur; public Association (Object c, Object v) { clef = c; valeur = v; } } Code de test Date d = new Date (12, 4, 1970); Employe e1 = new Employe (); System.out.println (e1); Employe e2 = new Employe ("Muller", "Jacques", d, "Stock", "gestionnaire", 55000); System.out.println (e2); Employe e3 = new Employe ("Muller", "Jacques", d, "Stock", "gestionnaire", 55000); System.out.println (e3); System.out.println ("\nE1 = E2 ? " + e1.equals(e2)); System.out.println ("\nE2 = E3 ? " + e2.equals(e3)); Résultat Nom : Dupont Prenom : Pierre Date de naisssance : 1/1/1980 Departement : Ventes Fonction : vendeur Salaire : SFr. 60000.Nom : Muller Prenom : Jacques Date de naisssance : 12/4/1970 Departement : Stock Fonction : gestionnaire Salaire : SFr. 55000.Nom : Muller Prenom : Jacques Date de naisssance : 12/4/1970 Departement : Stock Fonction : gestionnaire Salaire : SFr. 55000.E1 = E2 ? false E2 = E3 ? true ©Laura Perret 17 / 31 public Object getClef () { return clef; } public Object getValeur () { return valeur; } public abstract boolean equals (Object o); public abstract String toString (); } Code Association.java public class Adresse extends Association { public Adresse (String nom, String tel) { super (nom, tel); } public boolean equals (Object o) { Association a = (Association) o; return ((String) clef).equals(a.getClef()) && ((String) valeur).equals(a.getValeur()); } public String toString () { return new String ("Clef : " + (String) clef + "\n" + "Valeur : " + (String) valeur); } } 05.11.2006 ©Laura Perret 18 / 31 05.11.2006 Code de test Adresse a1 = new Adresse ("Perret", "032 / 768 12 34"); Adresse a2 = new Adresse ("Perret", "032 / 768 12 34"); Adresse a3 = new Adresse ("Dupont", "032 / 731 12 66"); public void println () { System.out.println ("MonEntier : " + entier); } } Code de test MonEntier e = new MonEntier (7); e.println(); Résultat MonEntier : 7 System.out.println (a1 + "\n"); System.out.println (a2 + "\n"); System.out.println (a3); System.out.println ("\nA1 = A2 ? " + a1.equals(a2)); System.out.println ("\nA2 = A3 ? " + a2.equals(a3)); Résultat Clef : Perret Valeur : 032 / 768 12 34 Exercice 29 Code MonEntier.java package lp; public class MonEntier { private int entier; Clef : Perret Valeur : 032 / 768 12 34 public MonEntier (int e) { entier = e; } Clef : Dupont Valeur : 032 / 731 12 66 public int getEntier () { return entier; } A1 = A2 ? true A2 = A3 ? false Exercice 28 public String toString () { return new String ("MonEntier : " + entier); } Code Imprimable .java public interface Imprimable { public void println (); } public void println () { System.out.println ("lp." + toString()); } Code MonEntier .java public class MonEntier implements Imprimable { private int entier; } Code de test MonEntier e1 = new MonEntier (7); lp.MonEntier e2 = new lp.MonEntier (8); public MonEntier (int e) { entier = e; } e1.println(); e2.println(); Résultat MonEntier : 7 lp.MonEntier : 8 public int getEntier () { return entier; } ©Laura Perret 19 / 31 05.11.2006 ©Laura Perret 20 / 31 05.11.2006 Exercice 30 Code de test try { Date d1 = new Date ("12/04/1970"); System.out.println (d1); Code de Date.java protected String format = "\\d{1,2}/\\d{1,2}/(\\d\\d|\\d\\d\\d\\d)"; public Date (String d) throws FormatException { int i = 0, j = 0; if (formatCorrect (d)) { j = d.indexOf('/', i); jour = Integer.parseInt(d.substring (i, j)); Date d2 = new Date ("12.04.1970"); System.out.println (d2); } catch (FormatException e) { System.out.println (e); } Résultat 12/4/1970 FormatException: La chaine 12.04.1970 ne respecte pas le format \d{1,2}/\d{1,2}/(\d\d|\d\d\d\d) i = j+1; j = d.indexOf('/', i); mois = Integer.parseInt(d.substring (i, j)); i = j+1; annee = Integer.parseInt(d.substring (i)); Exercice 31 } else { throw new FormatException (d, format); } } private boolean formatCorrect (String d) { return d.matches(format); } Code FormatException.java public class FormatException extends Exception { public FormatException (String string, String format) { super (new String ("La chaine " + string + " ne respecte pas le format " + format)); } } ©Laura Perret 21 / 31 05.11.2006 Code public static void main(String args[]) { int i; if (args.length != 0) { i = Integer.parseInt(args[0]); System.out.println ("Le parametre d'execution vaut : " + i); } } Résultat java test 12 Le parametre d'execution vaut : 12 ©Laura Perret 22 / 31 05.11.2006 Exercice 32 Exercice 33 Code int i; double d; String s; InputStreamReader flux = new InputStreamReader (System.in); BufferedReader in = new BufferedReader (flux); Code String line = ""; try { System.out.print ("Saisie\n\nEntier : "); i = Integer.parseInt(in.readLine()); System.out.print ("Double : "); d = Double.parseDouble(in.readLine()); System.out.print ("Chaine : "); s = in.readLine(); System.out.println ("\nResultat\n\nEntier : " + i + "\nDouble : " + d + "\nChaine : " + s); } catch (IOException e) { System.out.println (e); } Résultat Saisie Entier : 12 Double : 3.141592 Chaine : test Resultat Entier : 12 Double : 3.141592 Chaine : test ©Laura Perret 23 / 31 05.11.2006 try { FileReader fluxE = new FileReader ("readme.txt"); BufferedReader in = new BufferedReader (fluxE); FileWriter fluxS = new FileWriter ("readme_copie.txt"); PrintWriter out = new PrintWriter (fluxS); while (line != null) { line = in.readLine(); if (line != null) out.println(line); } in.close(); out.close(); System.out.println ("Fichier copie"); } catch (IOException e) { System.out.println (e); } Résultat Fichier copie ©Laura Perret 24 / 31 05.11.2006 Code de test Personne pin = new Personne ("Berger", "Pierre-Yves", new Date (6, 1, 1970)); Personne pout = null; String fichier = "personne.ser"; Exercice 34 Code Date.java import java.io.*; public class Date implements Serializable { private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(jour); out.writeInt(mois); out.writeInt(annee); } try { FileOutputStream fileOut = new FileOutputStream (fichier); ObjectOutputStream out = new ObjectOutputStream (fileOut); out.writeObject(pin); out.close(); private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { jour = in.readInt(); mois = in.readInt(); annee = in.readInt(); } FileInputStream fileIn = new FileInputStream (fichier); ObjectInputStream in = new ObjectInputStream (fileIn); pout = (Personne) in.readObject(); in.close(); } Code Personne.java System.out.println (pout); } catch (Exception e) { System.out.println (e); } Résultat Nom : Berger Prenom : Pierre-Yves Date de naisssance : 6/1/1970 import java.io.*; public class Personne implements Serializable { private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(nom); out.writeObject(prenom); out.writeObject(naissance); } Exercice 35 Code ImageGraphique.java import javax.swing.*; public class ImageGraphique extends JFrame { public ImageGraphique (String image) { super (image); JLabel img = new JLabel (new ImageIcon (image)); getContentPane().add(img); addWindowListener (new Adaptateur()); } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { nom = (String)in.readObject(); prenom = (String)in.readObject(); naissance = (Date)in.readObject(); } } ©Laura Perret 25 / 31 05.11.2006 ©Laura Perret 26 / 31 05.11.2006 private int annee; /** Cette propriété contient le format de date jj/mm/aaaa.*/ protected String format = "\\d{1,2}/\\d{1,2}/(\\d\\d|\\d\\d\\d\\d)"; private Pattern motif = Pattern.compile(format); Code Adaptateur.java import java.awt.*; import java.awt.event.*; public class Adaptateur extends WindowAdapter { public void windowClosing (WindowEvent e) { Window w = (Window) e.getSource(); w.dispose(); } } Code de test ImageGraphique image = new ImageGraphique ("cosmos.jpg"); image.setSize(300, 300); image.setLocation(100, 100); image.setVisible(true); Résultat Exercice 36 /**Cette classe réalise une simple date au format jj/mm/aaaa. @author Laura Perret @version 1.0 18th August 2003 @see java.util */ public class Date implements Serializable { /** Cette propriété contient le jour.*/ private int jour; /** Cette propriété contient le mois.*/ private int mois; /** Cette propriété contient l'annee.*/ 27 / 31 /** Constructeur paramétré. @param j le jour @param m le mois @param a l'année */ public Date (int j, int m, int a) { jour = j; mois = m; annee = a; } /** Constructeur paramétré à partir d'une chaîne de caractères. @param d une chaîne contenant une date @throws FormatException */ public Date (String d) throws FormatException { int i = 0, j = 0; if (FormatCorrect (d)) { j = d.indexOf('/', i); jour = Integer.parseInt(d.substring (i, j)); i = j+1; j = d.indexOf('/', i); mois = Integer.parseInt(d.substring (i, j)); i = j+1; annee = Integer.parseInt(d.substring (i)); } Code Date.java import java.util.regex.*; import java.io.*; ©Laura Perret /** Constructeur par défaut.*/ public Date () { jour = 1; mois = 1; annee = 1980; } 05.11.2006 ©Laura Perret 28 / 31 05.11.2006 else { throw new FormatException (d, format); } /** Compare l'objet à la date. @param o un objet auquel comparer la date @return un booleen, vrai si l'objet passé en paramètres est égal à la date, faux sinon. */ public boolean equals (Object o) { Date d = (Date) o; return d.jour == jour && d.mois == mois && d.annee == annee; } } private boolean FormatCorrect (String d) { return d.matches(format); } /** Retourne le jour. @return un entier qui représente le jour */ public int getJour () { return jour; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(jour); out.writeInt(mois); out.writeInt(annee); } /** Retourne le mois. @return un entier qui représente le mois */ public int getMois () { return mois; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { jour = in.readInt(); mois = in.readInt(); annee = in.readInt(); } /** Retourne l'année. @return un entier qui représente l'année */ public int getAnnee () { return annee; } } Code de test Date d = new Date (12, 5, 1971); System.out.println (d); /** Retourne la date sous forme de chaîne de caractères. @return une chaîne de caractères qui représente la date */ public String toString () { return new String (jour + "/" + mois + "/" + annee); } ©Laura Perret 29 / 31 05.11.2006 ©Laura Perret 30 / 31 05.11.2006 Résultat javadoc -d Docs -author -version -link http://java.sun.com/j2se/1.4.2/docs/api/ Date.java ©Laura Perret 31 / 31 05.11.2006