Tp2_java :
Mouhib_ifaoui
Ex1 :
import java.util.*; // Pour Scanner
// Lit deux réels et affiche le maximum (avec message si égalité)
public class Ex1_MaxDeuxReels {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Donnez a : ");
double a = sc.nextDouble(); // Lit a
System.out.print("Donnez b : ");
double b = sc.nextDouble(); // Lit b
// Math.max est simple et lisible
double max = Math.max(a, b);
System.out.println("Max(a,b) = " + max);
// Info utile en cas d'égalité
if (a == b) {
System.out.println("Remarque : a et b sont égaux.");
}
sc.close(); // Bonne pratique
}
}
Ex2 :
import java.util.*; // Pour Scanner
// Calcule sqrt(x) en gérant x négatif (pas de racine réelle)
public class Ex2_RacineCarree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Donnez un réel x : ");
double x = sc.nextDouble(); // Lit x
if (x < 0) { // Cas interdit en réels
System.out.println("Pas de racine carrée réelle pour x < 0.");
} else {
double r = Math.sqrt(x); // Racine carrée
System.out.println("sqrt(" + x + ") = " + r);
}
sc.close(); // Fermer le Scanner
}
}
Ex3 :
// Affiche les valeurs qui apparaissent exactement 1 fois (double boucle, version débutant)
public class Ex3_Uniques {
public static void main(String[] args) {
int[] t = {4, 2, 4, 7, 9, 2, 5, 9, 8}; // Tableau d'exemple
System.out.print("Éléments uniques : ");
boolean auMoinsUn = false; // Pour savoir si on a trouvé au moins un unique
// Parcourt chaque valeur t[i]
for (int i = 0; i < t.length; i++) {
int compteur = 0; // Compte combien de fois t[i] existe dans tout t
// Compare t[i] avec tous les éléments t[j]
for (int j = 0; j < t.length; j++) {
if (t[i] == t[j]) {
compteur++; // Incrémente si égal
}
}
// Unique = apparaît exactement 1 seule fois
if (compteur == 1) {
System.out.print(t[i] + " ");
auMoinsUn = true;
}
}
if (!auMoinsUn) System.out.print("(aucun)");
System.out.println(); // Saut de ligne
}
}
Ex4 :
import java.util.*; // Pour Scanner
// Supprime l'élément d'indice pos en décalant à gauche (taille logique)
public class Ex4_SupprimerPosition {
public static void main(String[] args) {
int[] t = {10, 20, 30, 40, 50}; // Tableau initial
int taille = t.length; // Taille "utile" actuelle
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Indice à supprimer (0.." + (taille - 1) + ") : ");
int pos = sc.nextInt(); // Lit l'indice à supprimer
if (pos < 0 || pos >= taille) { // Vérif bornes
System.out.println("Indice invalide.");
sc.close();
return; // On sort
}
// Décale vers la gauche à partir de pos
for (int i = pos; i < taille - 1; i++) {
t[i] = t[i + 1];
}
taille--; // Un élément "perdu" en fin (doublon)
// Affiche uniquement la partie utile (0..taille-1)
System.out.print("Après suppression : [");
for (int i = 0; i < taille; i++) {
System.out.print(t[i]);
if (i < taille - 1) System.out.print(", ");
}
System.out.println("]");
sc.close(); // Fermer scanner
}
}
Ex5 :
import java.util.*; // Pour Scanner
// Teste si une chaîne est un palindrome (ignore espaces + casse)
public class Ex5_Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Chaîne : ");
String s = sc.nextLine(); // Lit toute la ligne (espaces inclus)
// Nettoyage simple : enlever espaces et mettre en minuscule
String n = s.replace(" ", "").toLowerCase();
// Deux pointeurs : i au début, j à la fin
int i = 0, j = n.length() - 1;
boolean palindrome = true; // On suppose vrai au départ
// Compare les caractères symétriques
while (i < j) {
if (n.charAt(i) != n.charAt(j)) { // Dès différence → pas palindrome
palindrome = false;
break; // Inutile de continuer
}
i++; // Avancer début
j--; // Reculer fin
}
System.out.println(palindrome ? "Palindrome" : "Non palindrome");
sc.close(); // Fermer scanner
}
}
Ex6 :
// Extrait "Bonjour", "bienvenue" et "2IoT" sans indices magiques (indexOf + substring)
public class Ex6_Substring {
public static void main(String[] args) {
String s = "Bonjour, bienvenue au 2IoT !"; // Chaîne source
// "Bonjour" : du début jusqu'à longueur du mot
String bonjour = s.substring(0, "Bonjour".length());
// "bienvenue" : trouver l'index de début, puis couper à la bonne longueur
int debBienvenue = s.indexOf("bienvenue");
String bienvenue = s.substring(debBienvenue, debBienvenue + "bienvenue".length());
// "2IoT" : même logique
int deb2IoT = s.indexOf("2IoT");
String deuxIoT = s.substring(deb2IoT, deb2IoT + "2IoT".length());
// Affichages demandés
System.out.println("La sous-chaîne est : " + bonjour);
System.out.println("La sous-chaîne est : " + bienvenue);
System.out.println("La sous-chaîne est : " + deuxIoT);
}
}
Ex7 :
import java.util.*; // Pour Scanner
// Calcule l'aire d'un triangle : aire = (base * hauteur) / 2
public class Ex7_AireTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Base (b) : ");
double b = sc.nextDouble(); // Lit base
System.out.print("Hauteur (h) : ");
double h = sc.nextDouble(); // Lit hauteur
if (b < 0 || h < 0) { // Vérif valeurs
System.out.println("Erreur : b et h doivent être >= 0.");
} else {
double aire = (b * h) / 2.0; // 2.0 pour éviter division entière
System.out.println("Aire = " + aire);
}
sc.close(); // Fermer scanner
}
}
Ex8 :
import java.util.*; // Pour Scanner
// Vérifie si un entier n est premier (test des diviseurs jusqu'à sqrt(n))
public class Ex8_Premier {
// Retourne true si n est premier, false sinon
static boolean estPremier(int n) {
if (n < 2) return false; // 0,1, négatifs → pas premiers
int limite = (int) Math.sqrt(n); // On teste jusqu'à la racine carrée
for (int d = 2; d <= limite; d++) { // d = 2..√n
if (n % d == 0) return false; // Diviseur trouvé → composite
}
return true; // Aucun diviseur → premier
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Lecteur clavier
System.out.print("Entier n : ");
int n = sc.nextInt(); // Lit n
System.out.println(estPremier(n) ? "Premier" : "Non premier");
sc.close(); // Fermer scanner
}
}