TD serie I
Transcription
TD serie I
TD JAVA Master CSI sExercice 1 : Hello World Ecrire un programme qui affiche le message Hello World. Solution : package com.elghazi.master.basics; // A unique class name prefix public class Hello { // Everything in Java is a class public static void main(String[] args) { // All programs must have main() System.out.println("Hello World!"); // Say hello! } // This marks the end of main() } // Marks the end of the class Exercice 2 : FizzBuzz Il s’agit d’un jeu pour apprendre à compter le principe est le suivant : Les joueurs comptent à tour de rôle en commençant par le chiffre un jusqu'à le chiffre cent Les règles sont simple : si le nombre est un multiple de cinq il faut dire le mot « Fizz » à la place du chiffre, si le nombre est un multiple de sept il faut dire « Buzz ».s’il s’agit d’un multiple des deux, il faut dire « FizzBuzz ». Ecrire un programme qui joue à ce jeu. Solution : package com.elghazi.master.basics; public class FizzBuzz { // Everything in Java is a class public static void main(String[] args) { // Every program must have main() for(int i = 1; i <= 100; i++) { // count from 1 to 100 if (((i % 5) == 0)&& ((i % 7) == 0)) // Is it a multiple of 5 & 7? System.out.print("fizzbuzz"); else if ((i % 5) == 0) // Is it a multiple of 5? System.out.print("fizz"); else if ((i % 7) == 0) // Is it a multiple of 7? System.out.print("buzz"); else System.out.print(i); // Not a multiple of 5 or 7 System.out.print(" "); } System.out.println(); } } Exercice 3 : les séries de Fibonacci Définition : les nombres de Fibonacci représentent une suite de nombres ou chaque nombre consécutif est la somme des deux nombres precedents.la séquence commence par 1,1,2,3,5, 8,13…et se poursuit en suivant la même règle. Ecrire un programme qui calcule et affiche les 20 premiers nombres de Fibonacci. Solution : A.ELGH@ZI Page 1 TD JAVA Master CSI package com.elghazi.master.basics; /** * This program prints out the first 20 numbers in the Fibonacci sequence. * Each term is formed by adding together the previous two terms in the * sequence, starting with the terms 1 and 1. **/ public class Fibonacci { public static void main(String[] args) { int n0 = 1, n1 = 1, n2; // Initialize variables System.out.print(n0 + " " + // Print first and second terms n1 + " "); // of the series for(int i = 0; i < 18; i++) { // Loop for the next 18 terms n2 = n1 + n0; // Next term is sum of previous two System.out.print(n2 + " ");// Print it out n0 = n1; // First previous becomes 2nd previous n1 = n2; // And current number becomes previous } System.out.println(); // Terminate the line } } Exercice 4 : Echo Ecrire un programme qui Echo qui lit ces arguments et les affiche en retour. Par exemple : On donne « Bonjour Monsieur Elghazi » comme paramètre de la méthode main Le programme Echo répondra : « Bonjour Monsieur Elghazi » Solution : package com.elghazi.master.basics; /** * This program prints out all its command-line arguments. **/ public class Echo { public static void main(String[] args) { int i = 0; // Initialize the loop variable while(i < args.length) { // Loop until the end of array System.out.print(args[i] + " ");// Print each argument out i++; // Increment the loop variable } System.out.println(); // Terminate the line } } Exercice 5 : Echo inversé Cette fois le programme Echo affichera les arguments dans l’ordre inverse Exemple : On donne « bonjour Monsieur Elghazi » Echo répondra : « izahgle rueisnom ruojnob » A.ELGH@ZI Page 2 TD JAVA Master CSI Solution : package com.elghazi.master.basics; /** * This program echos the command-line arguments backwards. **/ public class Reverse { public static void main(String[] args) { // Loop backwards through the array of arguments for(int i = args.length-1; i >= 0; i--) { // Loop backwards through the characters in each argument for(int j=args[i].length()-1; j>=0; j--) { // Print out character j of argument i. System.out.print(args[i].charAt(j)); } System.out.print(" ");// Add a space at the end of each argument. } System.out.println(); // And terminate the line when we're done. } } Exercice 6 : FizzBuzz revisité Donner un programme qui joue à FizzBuzz on utilisant l’instruction Switch à la place des instructions If/else. Solution: package com.elghazi.master.basics; /** * This class is much like the FizzBuzz class, but uses a switch statement * instead of repeated if/else statements **/ public class FizzBuzz2 { public static void main(String[] args) { for(int i = 1; i <= 100; i++) { // count from 1 to 100 switch(i % 35) { // What's the remainder when divided by 35? case 0: // For multiples of 35... System.out.print("fizzbuzz "); // print "fizzbuzz". break; // Don't forget this statement! case 5: case 10: case 15: // If the remainder is any of these case 20: case 25: case 30:// then the number is a multiple of 5 System.out.print("fizz "); // so print "fizz". break; case 7: case 14: case 21: case 28: // For any multiple of 7... System.out.print("buzz "); // print "buzz". break; default: // For any other number... System.out.print(i + " "); // print the number. break; } } System.out.println(); A.ELGH@ZI Page 3 TD JAVA Master CSI } } Exercice 7 : calcul des factoriels Ecrire un programme qui calcul le factoriel d’un entier positif. Remarque : le programme est une classe Factorial, qui contient une méthode factorial (). Solution: package com.elghazi.master.basics; /** *This class doesn't define a main() method, so it isn't a program by itself. * It does define a useful method that we can use in other programs, though. **/ public class Factorial { /** Compute and return x!, the factorial of x */ public static int factorial(int x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); int fact = 1; for(int i = 2; i <= x; i++) // loop fact *= i; // shorthand for: fact = fact * i; return fact; } } Exercice 8: Factoriels récursifs La même chose que l’exercice précédent mais cette fois avec une méthode récursive et les données de types long. Solution: package com.elghazi.master.basics; /** * This class shows a recursive method to compute factorials. This method * calls itself repeatedly based on the formula: n! = n * (n-1)! **/ public class Factorial2 { public static long factorial(long x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); if (x <= 1) return 1; // Stop recursing here else return x * factorial(x-1); // Recurse by calling ourselves } } A.ELGH@ZI Page 4 TD JAVA Master CSI Exercice 9: Trier les nombres Ecrire un algorithme simple (une méthode) pour trier un tableau de nombres, Puis écrire un simple programme pour tester l’algorithme précédent. Solution: package com.elghazi.master.basics; /** * This class demonstrates how to sort numbers using a simple algorithm **/ public class SortNumbers { /** * This is a very simple sorting algorithm that is not very efficient * when sorting large numbers of things **/ public static void sort(double[] nums) { // Loop through each element of the array, sorting as we go. // Each time through, find the smallest remaining element, and move it // to the first unsorted position in the array. for(int i = 0; i < nums.length; i++) { int min = i; // holds the index of the smallest element // find the smallest one between i and the end of the array for(int j = i; j < nums.length; j++) { if (nums[j] < nums[min]) min = j; } // Now swap the smallest one with element i. // This leaves all elements between 0 and i sorted. double tmp; tmp = nums[i]; nums[i] = nums[min]; nums[min] = tmp; } } /** This is a simple test program for the algorithm above */ public static void main(String[] args) { double[] nums = new double[10]; // Create an array to hold numbers for(int i = 0; i < nums.length; i++) // Generate random numbers nums[i] = Math.random() * 100; sort(nums); // Sort them for(int i = 0; i < nums.length; i++) // Print them out System.out.println(nums[i]); } } A.ELGH@ZI Page 5