Vous êtes sur la page 1sur 12

TD_TP_1 (Corrigé exercices de base) POO JAVA

Université Moulay Ismaïl 2021-2022


ENSAM – Meknès S2– TC3A

Exercice 1 : Exercice 4 :

Ecrire un programme Java qui vérifie si un nombre Réaliser une classe Point permettant de
entier à 3 chiffres fourni au clavier est un nombre représenter un point sur un axe. Chaque point
Armstrong ou non, sera caractérisé par un nom (de type char) et
une abscisse (de type double).
Il affiche en sortie :
On prévoira :
Le nombre x est un nombre Armstrong
• un constructeur recevant en arguments le
Ou : le nombre x n’est pas un nombre Armstrong nom et l’abscisse d’un point,

Déf d’un nombre Armstrong : • une méthode affiche imprimant (en fenêtre
console) le nom du point et son abscisse,
153 et 371 sont dits nombres Armstrong car :
• une méthode translate effectuant une
153= (1*1*1)+(5*5*5)+(3*3*3) translation définie par la valeur de son
argument.
371=(3*3*3)+(7*7*7)+(1*1*1)
Écrire un petit programme utilisant cette
221 n’est pas un nombre Armstrong car classe pour créer un point, en afficher les
caractéristiques, le déplacer et en afficher à
221 !=(2*2*2)+(2*2*2)+(1*1*1) nouveau les caractéristiques

Exercice 2 :
Exercice 5 :
Déclarer la classe Student avec les 2 attributs
name et college (de type chaine de caractères) Ecrire un programme java qui permet
d’inverser une chaine ce caractère (utiliser
Définir tous les constructeurs possibles de plusieurs méthodes)
cette classe,
Résultat d’exécution
On fait un test d'exécution en instanciant et
ENSAM 3A
initialisant des objets de type Student en A3 MASNE
utilisant à chaque fois un constructeur
différent. Exercice 6 :

Exercice 3 Ecrire un programme java qui calcule et affiche


le nombre d’occurrence d’un mot dans une
Ecrire un programme Java qui retourne le plus chaine de caractère (phrase)
grand commun diviseur de deux entiers saisis
au clavier (utiliser la classe nommée Pgcd) Résultat d’exécution

Count number of occurrences of


Exemple d’exécution :
substring 'ensam' in string 'ensam
ecole d'ingénieur' : 1
Entrer premier Nombre:4
Entrer deuxieme Nombre:2 Count number of occurrences of
Le plus grand commun diviseur est: 2 substring 'ensam' in string 'ensam 3A,
ensam 4A' : 2

S.Amri & M.Hosni P a g e 1 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

Exercice 7: 1
2
Ecrire un programme Java qui vérifie si 10
un mot donné est palindrome ou non. 20
30
Un mot est dit palindrome si il est 40
lisible de gauche à droite comme de 50
droite à gauche (exp :radar)
Exercice 10
Résultat d’exécution :
Que fournit le programme suivant ?
madam is palindrome = true
abcba is palindrome = true class Entier {
public Entier (int nn) { n = nn ; }
abc is palindrome = false
public void incr (int dn) { n += dn ;
}
Exercice 8 : public void imprime () {
System.out.println (n) ; }
Ecrire un programme Java qui private int n ;
permet de permuter deux chaines }
de caractères, et affiche le public class TstEnt {
contenu résultat. public static void main (String
args[]) { Entier n1 = new Entier (2) ;
System.out.print ("n1 = ") ;
Résultat d’exécution n1.imprime() ;
Entier n2 = new Entier (5) ;
before swapping two strings System.out.print ("n1 = ") ;
s1 => ENSAM n2.imprime() ;
s2 => Meknes n1.incr(3) ;
after swapping two strings System.out.print ("n1 = ") ;
s1 => Meknes n1.imprime() ;
s2 => ENSAM System.out.println ("n1 == n2 est " +
(n1 == n2)) ;
Exercice 9 n1 = n2 ;
n2.incr(12) ;
Ecrire un programme Java qui vérifie si System.out.print ("n2 = ") ;
deux tableaux sont identiques et n2.imprime() ;
affiche le résultat de la vérification. System.out.print ("n1 = ") ;
n1.imprime() ;
Résultat d’exécution : System.out.println ("n1 == n2 est " +
(n1 == n2)) ;
Two Integers are Equal :: false }
}
Exercice 9:
Exercice 11 :
Ecrire un programme Java qui permet de
trier un tableau d’entiers donné, On suppose qu’on dispose de la classe A ainsi
supprime les doublons et affiche le définie :
tableau résultat.

Tableau donné par exp. : {50, 30, 1,10,


class A {
20, 30,2, 40,1, 50, 2,10, 20} void f (int n, float x) { ..... }
void g (byte b) { ..... } .....
Résultat d’exécution : }
Soit ces déclarations :
Le tableau trié sans doublons est :

S.Amri & M.Hosni P a g e 2 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

A a ;int n; byte b ;float x ; - Constructeur, recevant en argument


double y;
l’abscisse "absolue" du point (c’est-à-dire
Dire si les appels suivants sont corrects et sinon repérée par rapport au point d’origine 0 et
pourquoi ?
non par rapport à l’origine courante),
a.f (n, x) ; - affiche qui imprime à la fois l’abscisse de
a.f (b+3, x) ;
a.f (b, x) ; l’origine courante et l’abscisse du point par
a.f (n, y) ; rapport à cette origine,
a.f (n, (float)y) ;
a.f (n, 2*x) ; - setOrigine qui permet de définir une
a.f (n+5, x+0.5) ; nouvelle abscisse pour l’origine (exprimée
a.g (b) ;
a.g (b+1) ; de façon absolue et non par rapport à
a.g (b++) ;
l’origine courante),
a.g (3) ;
- getOrigine qui permet de connaître
Exercice 12 : l’abscisse de l’origine courante.
- Ecrire un petit programme de test
Créer une classe permettant de manipuler un fournissant les résultats suivants :
point d’un axe, repéré par une abscisse (de
Point a - abscisse = 3
type int). relative a une origine d'abscisse 0
Point b - abscisse = 12
On devra pouvoir effectuer des changements relative a une origine d'abscisse 0
d’origine, en conservant en permanence On place l'origine en 3
Point a - abscisse = 0
l’abscisse d’une origine courante (initialement relative a une origine d'abscisse 3
Point b - abscisse = 9
0). relative a une origine d'abscisse 3
On prévoira simplement les méthodes
suivantes :

S.Amri & M.Hosni P a g e 3 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

Exercice 1 :

import java.util.Scanner;

/**
* Java Program to Check Armstrong Number
*
*
*/
public class ArmstronNombre {
public static void main(String[] args) {

try (Scanner scanner = new Scanner(System.in)) {


int temp, total = 0;
System.out.println("Entrer Nombre à 3 chiffres : ");
int num = scanner.nextInt();
int number = num;

for (; number != 0; number /= 10) {


temp = number % 10;
total = total + temp * temp * temp;
}

if (total == num) {
System.out.println(num + " est un nombre Armstrong");
} else {
System.out.println(num + " n'est pas un nombre Armstrong");
}
}
}

Exercice 2 :
public class Student {
private String name;
private String college;

public Student(String name, String college) {


super();
this.name = name;
this.college = college;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getCollege() {

S.Amri & M.Hosni P a g e 4 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

return college;
}

public void setCollege(String college) {


this.college = college;
}

public static void main(String[] args) {

Student student1 = new Student("Mohamed", "ENSAM");


Student student2 = new Student("Rachid", "EST");
Student student3 = new Student("Fatima", "ENCG");
}

Exercice 3 :
import java.util.Scanner;
public class PGCD {
public static void main(String[] args) {

try (Scanner scanner = new Scanner(System.in)) {


int num1, num2;
System.out.print("Entrer premier Nombre:");
num1 = (int) scanner.nextInt();

System.out.print("Entrer deuxieme Nombre:");


num2 = (int) scanner.nextInt();

// closing the scanner to avoid memory leaks


scanner.close();
while (num1 != num2) {
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

// displaying the result


System.out.printf("Le plus grand commun diviseur est: %d", num2);
}
}

Exercice 4
class Point {
public Point (char c, double x) // constructeur
{ nom = c ; abs = x ; }
public void affiche () {
System.out.println ("Point de nom " + nom + " d'abscisse " + abs) ;
}
public void translate (double dx) {
abs += dx ;
S.Amri & M.Hosni P a g e 5 | 12
TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

}
private char nom ; // nom du point
private double abs ; // abscisse du point
}
public class TstPtAxe {
public static void main (String args[]) {
Point a = new Point ('C', 2.5) ;
a.affiche() ;
Point b = new Point ('D', 5.25) ;
b.affiche() ;
b.translate(2.25) ;
b.affiche() ;
}
}

Point de nom C d'abscisse 2.5


Point de nom D d'abscisse 5.25
Point de nom D d'abscisse 7.5

Exercice 5 :
/* 5 ways to reverse a String in Java
/* @author java ENSAM 3A
*
*/
public class ReverseString5Ways {

public static void main(String[] args) {


reverseWithStringConcat("ENSAM 3A");
reverseWithStringBuilder("ENSAM 3A");
reverseWithStringBuilderBuiltinMethod("ENSAM 3A");
reverseWithSwaps("ENSAM 3A");
reverseWithXOR("ENSAM 3A");
}

public static final String reverseWithStringConcat(String string) {


String output = new String();
for (int i = (string.length() - 1); i >= 0; i--) {
output += (string.charAt(i));
}

display(string, output);
return output;
}

public static final String reverseWithStringBuilder(String string) {


final StringBuilder builder = new StringBuilder();
for (int i = (string.length() - 1); i >= 0; i--) {
builder.append(string.charAt(i));
}
display(string, builder.toString());
return builder.toString();
}

S.Amri & M.Hosni P a g e 6 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

public static final String reverseWithStringBuilderBuiltinMethod(String


string) {
final StringBuilder builder = new StringBuilder(string);
display(string, builder.reverse().toString());
return builder.reverse().toString();
}

public static final String reverseWithSwaps(String string) {


final char[] array = string.toCharArray();
final int length = array.length - 1;
final int half = (int) Math.floor(array.length / 2);

char c;
for (int i = length; i >= half; i--) {
c = array[length - i];
array[length - i] = array[i];
array[i] = c;
}
display(string, String.valueOf(array));
return String.valueOf(array);
}

public static final String reverseWithXOR(String string) {


final char[] array = string.toCharArray();
final int length = array.length;
final int half = (int) Math.floor(array.length / 2);

for (int i = 0; i < half; i++) {


array[i] ^= array[length - i - 1];
array[length - i - 1] ^= array[i];
array[i] ^= array[length - i - 1];
}
display(string, String.valueOf(array));
return String.valueOf(array);
}

private static final void display(String original, String reverse) {


System.out.println(original);
System.out.println(reverse);
System.out.println("----------------------------");
}

Exercice 6
public class CountOccuranceOfSubString {

public static void main(String[] args) {


int count = countOccurrencesOf("ensam ecole d'ingénieur", "ensam");
System.out.println("Count number of occurrences of substring 'ensam' " +
" in string 'ensam ecole d'ingénieur' : " + count);
int count1 = countOccurrencesOf("ensam 3A, ensam 4A", "ensam");
System.out.println("Count number of occurrences of substring 'ensam'" +
" in string 'ensam 3A, ensam 4A' : " + count1);

S.Amri & M.Hosni P a g e 7 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

public static boolean hasLength(String str) {


return (str != null && !str.isEmpty());
}

public static int countOccurrencesOf(String str, String sub) {


if (!hasLength(str) || !hasLength(sub)) {
return 0;
}

int count = 0;
int pos = 0;
int idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}

Exercice 7
public class StringPalindromeProgram {

private static boolean isEmpty(final String cs) {


return cs == null || cs.length() == 0;
}

public static boolean checkPalindrome(String input) {

// Check error conditions


if (isEmpty(input)) {
return false;
}
String reverse = "";
int length = input.length();

for (int i = length - 1; i >= 0; i--) {


reverse = reverse + input.charAt(i);
}

if (input.equals(reverse)) {
System.out.println(input + " is palindrome = " + true);
} else {
System.out.println(input + " is palindrome = " + false);
}
return false;
}

public static void main(String[] args) {


checkPalindrome("madam");
checkPalindrome("abcba");
checkPalindrome("abc");

S.Amri & M.Hosni P a g e 8 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

Exercice 8
public class PermutTwoChaines {

public static void main(String[] args) {

String s1 = "ENSAM";
String s2 = "Meknes";

System.out.println(" before swapping two strings ");


System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);

// step 1: concat s1 + s2 and s1

s1 = s1 + s2; // ENSAM Meknes

// Step 2: store initial value of s1 into s2


s2 = s1.substring(0, s1.length() - s2.length()); // 0, 11-5 //ENSAM

// Step 3: store inital value of s2 into s1


s1 = s1.substring(s2.length());

System.out.println(" after swapping two strings ");


System.out.println(" s1 => " + s1);
System.out.println(" s2 => " + s2);
}

Exercice 9
public class CheckTwoArraysAreEqual {

public static void main(final String[] args) {

final int[] array1 = { 1, 2, 3, 4, 5,6 };


final int[] array2 = { 1, 2, 3, 4, 5 };

final boolean intCheck = equals(array1, array2);


System.out.println("Two Integers are Equal :: " + intCheck);
}

public static boolean equals(final int[] a, final int[] a2) {


if (a == a2)
return true;
if (a == null || a2 == null)
return false;

final int length = a.length;


if (a2.length != length)
return false;
S.Amri & M.Hosni P a g e 9 | 12
TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

for (int i = 0; i < length; i++)


if (a[i] != a2[i])
return false;

return true;
}

Exercice 10
import java.util.Arrays;

public class DuplicateFromArray {

public static void main(final String[] args) {

final int[] a = { 50, 30, 1,10, 20, 30,2, 40,1, 50, 2,10, 20 };
Arrays.sort(a);// sorting array
removeDuplicate(a);
}

private static void removeDuplicate(final int[] a) {

final int[] temp = new int[a.length];

int j = 0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
temp[j++] = a[i];
}
}
temp[j++] = a[a.length - 1];

for (int i = 0; i < j; i++) {


a[i] = temp[i];
}
System.out.println("Le tableau trié sans doublons est:");
for (int i = 0; i < j; i++) {
System.out.println(temp[i]);
}
}

Exercice 11

n1 = 2
n1 = 5
n1 = 5
n1 == n2 est false
n2 = 17
S.Amri & M.Hosni P a g e 10 | 12
TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

n1 = 17
n1 == n2 est true

L’opérateur == appliqué à des objets compare leurs références (et non leurs valeurs). C’est pourquoi
la première comparaison (n1 == n2) est fausse alors que les objets ont la même valeur. La même
réflexion s’applique à l’opérateur d’affectation. Après exécution de n1 = n2, les références contenues
dans les variables n1 et n2 sont les mêmes.

L’objet anciennement référencé par n2 n’étant plus référencé par ailleurs, il devient candidat au
ramasse-miettes. Dorénavant n1 et n2 référencent un seul et même objet. L’incrémentation de sa
valeur par le biais de n1 se retrouve indifféremment dans n1.imprime et dans n2.imprime.

De même, la comparaison n1 == n2 a maintenant la valeur vrai.

Exercice 12 :

a.f (n, x) ; // OK : appel normal


a.f (b+3, x) ; // OK :
b+3 est déjà de type int
a.f (b, x) ; // OK : b de type byte sera converti en int
a.f (n, y) ; // erreur : y de type double ne peut être converti en float
a.f (n, (float)y) ; // OK
a.f (n, 2*x) ; // OK : 2*x est de type float
a.f (n+5, x+0.5) ; // erreur : 0.5 est de type double, donc x+0.5 est de
type double, lequel ne peut pas être converti en float
a.g (b) ; // OK : appel normal
a.g (b+1) ; // erreur : b1+1 de type int ne peut être converti en byte
a.g (b++) ; // OK : b1++ est de type int (mais peu conseillé : on a modifié
la valeur de b1)
a.g (3) ; // erreur : 3 de type int ne peut être convertie en byte

Exercice 12 :

L’abscisse de l’origine courante est une information qui concerne tous les points de la classe. On en
fera donc un champ de classe en le déclarant static. De la même manière, les méthodes setOrigine et
getOrigine concernent non pas un point donné, mais la classe.

On en fera des méthodes de classe en les déclarant static.

class Point {
public Point (int xx) { x = xx ;
}
public void affiche ()
{ System.out.println ("abscisse = " + (x-origine)) ;
System.out.println (" relative a une origine d'abscisse " + origine) ;
}
public static void setOrigine (int org) { origine = org ; }
public static int getOrigine() { return origine ; }
private static int origine ; // abscisse absolue de l'origine courante
private int x ; // abscisse absolue du point
}

S.Amri & M.Hosni P a g e 11 | 12


TD_TP_1 (Corrigé exercices de base) POO JAVA
Université Moulay Ismaïl 2021-2022
ENSAM – Meknès S2– TC3A

public class TstOrig {


public static void main (String args[]) {
Point a = new Point (3);
System.out.print ("Point a - ") ;
a.affiche() ;
Point b = new Point (12) ;
System.out.print ("Point b - ") ;
b.affiche() ;
Point.setOrigine(3) ;
System.out.println ("On place l'origine en " + Point.getOrigine()) ;
System.out.print ("Point a - ") ;
a.affiche() ;
System.out.print ("Point b - ") ;
b.affiche() ;
}
}

S.Amri & M.Hosni P a g e 12 | 12

Vous aimerez peut-être aussi