Створення Власних Методів
Як використовувати методи?
Ми розглянули створення методу, який додає два числа. Тепер подивімося, як саме можна викликати цей метод у нашому коді:
Main.java
123456789101112131415161718192021package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { int a = 10; int b = 31; // use the method to add two numbers: `a` and `b` int sum = addTwoNumbers(a, b); // print the sum of the two numbers System.out.println(sum); } // method to add two numbers and return the result static int addTwoNumbers(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber; // return the result of the addition return result; } }
- Ми створили дві змінні типу
int
з різними значеннями та передали їх як параметри до нашого методу; - Оскільки наш метод повертає тип
int
, ми можемо ініціалізувати зміннуsum
результатом виклику методу; - Таким чином, наш метод обчислив і повернув
sum
двох чисел.
Ми також можемо передавати масиви як параметри та повертати їх з методів. Розглянемо приклад:
Main.java
1234567891011121314151617181920212223242526272829303132package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating an unsorted array int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; // use a method to sort the array and increment each element by 1 int[] newArray = sortAndIncrementEveryElement(array); // print the new array after sorting and incrementing each element for (int element : newArray) { System.out.print(element + " "); // output each element from the new array } } // method to increment each element of the array by 1 and then sort it static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }
Ми написали метод, який сортує та збільшує кожен елемент цілочисельного масиву (int[]
). Далі ми створюємо невідсортований масив і використовуємо цей метод для нього, ініціалізуючи новий масив під назвою newArray
повернутим значенням.
Варто зазначити, що цей метод можна використовувати кілька разів у тому ж коді, наприклад:
Main.java
1234567891011121314151617181920212223242526272829303132333435363738package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating unsorted arrays int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; int[] secondArray = {2, 2, 0, -5, 1, 8, 13, -9, 0}; // use a method to sort and increment each element in both arrays int[] newArray = sortAndIncrementEveryElement(array); int[] newSecondArray = sortAndIncrementEveryElement(secondArray); // print the new arrays after sorting and incrementing the elements for (int element : newArray) { System.out.print(element + " "); // output each element of the first array } System.out.println(System.lineSeparator()); for (int element : newSecondArray) { System.out.print(element + " "); // output each element of the second array } } // method to increment each element by 1 and then sort the array static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }
Отже, ми бачимо, що можемо використовувати наш метод декілька разів у коді. Ми застосували його до двох різних масивів цілих чисел, і кожен з них тепер відсортований та збільшений.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Awesome!
Completion rate improved to 2.63
Створення Власних Методів
Свайпніть щоб показати меню
Як використовувати методи?
Ми розглянули створення методу, який додає два числа. Тепер подивімося, як саме можна викликати цей метод у нашому коді:
Main.java
123456789101112131415161718192021package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { int a = 10; int b = 31; // use the method to add two numbers: `a` and `b` int sum = addTwoNumbers(a, b); // print the sum of the two numbers System.out.println(sum); } // method to add two numbers and return the result static int addTwoNumbers(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber; // return the result of the addition return result; } }
- Ми створили дві змінні типу
int
з різними значеннями та передали їх як параметри до нашого методу; - Оскільки наш метод повертає тип
int
, ми можемо ініціалізувати зміннуsum
результатом виклику методу; - Таким чином, наш метод обчислив і повернув
sum
двох чисел.
Ми також можемо передавати масиви як параметри та повертати їх з методів. Розглянемо приклад:
Main.java
1234567891011121314151617181920212223242526272829303132package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating an unsorted array int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; // use a method to sort the array and increment each element by 1 int[] newArray = sortAndIncrementEveryElement(array); // print the new array after sorting and incrementing each element for (int element : newArray) { System.out.print(element + " "); // output each element from the new array } } // method to increment each element of the array by 1 and then sort it static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }
Ми написали метод, який сортує та збільшує кожен елемент цілочисельного масиву (int[]
). Далі ми створюємо невідсортований масив і використовуємо цей метод для нього, ініціалізуючи новий масив під назвою newArray
повернутим значенням.
Варто зазначити, що цей метод можна використовувати кілька разів у тому ж коді, наприклад:
Main.java
1234567891011121314151617181920212223242526272829303132333435363738package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating unsorted arrays int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; int[] secondArray = {2, 2, 0, -5, 1, 8, 13, -9, 0}; // use a method to sort and increment each element in both arrays int[] newArray = sortAndIncrementEveryElement(array); int[] newSecondArray = sortAndIncrementEveryElement(secondArray); // print the new arrays after sorting and incrementing the elements for (int element : newArray) { System.out.print(element + " "); // output each element of the first array } System.out.println(System.lineSeparator()); for (int element : newSecondArray) { System.out.print(element + " "); // output each element of the second array } } // method to increment each element by 1 and then sort the array static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }
Отже, ми бачимо, що можемо використовувати наш метод декілька разів у коді. Ми застосували його до двох різних масивів цілих чисел, і кожен з них тепер відсортований та збільшений.
Дякуємо за ваш відгук!