Contenu du cours
Java Étendu
Java Étendu
Pratique des Méthodes
Pratique
Les méthodes peuvent être difficiles à comprendre, donc ce chapitre fournit des exemples de diverses méthodes en action, montrant comment elles fonctionnent, où les utiliser, et comment écrire et combiner plusieurs méthodes efficacement.
Exemple 1
Commençons par une méthode qui prend un tableau de type int
et le renverse de sorte que la dernière valeur devienne la première et la première devienne la dernière :
Main
package com.example; public class Main { static int[] flipIntArray(int[] array) { int[] result = new int[array.length]; int index = 0; for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } static void printIntArrayToTheConsole(int[] array) { for (int element : array) { System.out.print(element + " "); } System.out.println(); } public static void main(String[] args) { // do not modify the code below int[] firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] secondArray = {0, 2, 4, 6, 8, 10, 12, 14, 16}; printIntArrayToTheConsole(flipIntArray(firstArray)); printIntArrayToTheConsole(flipIntArray(secondArray)); } // do not modify the code above }
-
Tout d'abord, prêtons attention à la méthode
flipIntArray
à la ligne 4, qui utilise une boucle qui compte à partir de la fin du tableau et stocke ses valeurs dans un nouveau tableau de la même taille. Il y a aussi une variableindex
à la ligne 6 qui augmente pour stocker les valeurs dans le tableauresult
; -
Ensuite, vous pouvez voir la méthode à la ligne 14 du chapitre précédent, que j'utilise pour imprimer le tableau en une seule ligne de code ;
-
Maintenant, passons à quelque chose d'intéressant. Vous pouvez voir aux lignes 25-26 que je passe une méthode en tant que paramètre à l'intérieur d'une autre méthode. C'est parce que j'utilise une méthode qui retourne
int[]
à l'intérieur d'une méthode qui prendint[]
comme paramètre, économisant ainsi la mémoire allouée pour créer des variables. Nous pouvons voir que nos méthodes fonctionnent et affichent les valeurs correctes.
Exemple 2
Supposons que nous devions écrire une méthode qui calcule le factoriel, prenant une variable entière en entrée.
Main
package com.example; // do not modify the code below this comment public class Main { // method to calculate the factorial of a number static int calculateFactorial(int input) { int result = 1; // loop to calculate factorial by multiplying each number from 1 to input for (int i = 1; i <= input; i++) { result = result * i; } // return the final result of the factorial calculation return result; } public static void main(String[] args) { // initializing the first number for factorial calculation int first = 5; // initializing the second number for factorial calculation int second = 7; // initializing the third number for factorial calculation int third = 4; // calculating and printing the factorial of the first number System.out.println("Factorial of the first number = " + calculateFactorial(first)); // calculating and printing the factorial of the second number System.out.println("Factorial of the second number = " + calculateFactorial(second)); // calculating and printing the factorial of the third number System.out.println("Factorial of the third number = " + calculateFactorial(third)); } }
Dans cet exemple, nous avons écrit une méthode qui multiplie la variable accumulée par les nombres de 1
au nombre donné afin de calculer la factorielle. C'est une approche simple, et vous pouvez voir comment nous utilisons cette méthode plusieurs fois dans la méthode main
, ce qui économise de l'espace et améliore la lisibilité du code.
Ensuite, nous utilisons notre méthode à l'intérieur de System.out.println
car la méthode retourne une valeur int
.
Exemple 3
Nous allons écrire une méthode qui crée une abréviation à partir d'un tableau de chaînes de caractères.
Main
package com.example; // do not modify the code below this comment public class Main { // method to create abbreviation by taking first letter of each word static String makeAbbreviation(String[] input) { StringBuilder result = new StringBuilder(); // iterate through each word and append the first letter to result for (String word : input) { result.append(word.toUpperCase().charAt(0)); } // return the abbreviation as a string return result.toString(); } public static void main(String[] args) { // initializing arrays with words for abbreviation String[] firstArray = {"united", "nations"}; String[] secondArray = {"North", "Atlantic", "Treaty", "Organization"}; String[] thirdArray = {"Oh", "my", "God"}; // printing abbreviation for the first array System.out.println(makeAbbreviation(firstArray)); // printing abbreviation for the second array System.out.println(makeAbbreviation(secondArray)); // printing abbreviation for the third array System.out.println(makeAbbreviation(thirdArray)); } }
Dans cette méthode, nous utilisons la classe StringBuilder
pour appeler la méthode append()
et ajouter la première lettre en majuscule à une chaîne initialement vide. De cette manière, nous itérons à travers chaque élément du tableau, prenons la lettre à la position zéro (la première lettre de chaque mot), la convertissons en majuscule en utilisant la méthode toUpperCase()
, et l'ajoutons à notre résultat en utilisant la méthode append()
. Enfin, nous utilisons la méthode toString()
pour convertir notre StringBuilder
en String
.
1. Qu'est-ce qu'une valeur de retour dans une méthode ?
2. Que renvoie une méthode void
?
3. Une méthode peut-elle être utilisée à l'intérieur d'une autre méthode ?
Merci pour vos commentaires !