Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Metodeøvelser | Metoder
Java Udvidet

book
Metodeøvelser

Øvelse

Metoder kan være udfordrende at forstå, så dette kapitel giver eksempler på forskellige metoder i brug, viser hvordan de fungerer, hvor de anvendes, og hvordan man skriver og kombinerer flere metoder effektivt.

Eksempel 1

Lad os starte med en metode, der tager et array af typen int og vender det om, så sidste værdi bliver den første og første bliver den sidste:

Main.java

Main.java

copy
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
}
123456789101112131415161718192021222324252627282930
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 }
  • Først skal vi lægge mærke til metoden flipIntArray på linje 4, som bruger en løkke, der tæller fra slutningen af arrayet og gemmer værdierne i et nyt array af samme størrelse. Der er også en index-variabel på linje 6, der øges for at gemme værdierne i result-arrayet;

  • Dernæst kan du se metoden på linje 14 fra det forrige kapitel, som jeg bruger til at udskrive arrayet med kun én linje kode;

  • Nu går vi videre til noget interessant. Du kan se på linje 25-26, at jeg sender en metode som parameter ind i en anden metode. Dette skyldes, at jeg bruger en metode, der returnererint[] inde i en metode, der tagerint[] som parameter, hvilket sparer hukommelse ved ikke at oprette ekstra variabler. Vi kan se, at vores metoder fungerer og viser de korrekte værdier.

Eksempel 2

Antag, at vi skal skrive en metode, der beregner fakultet, hvor en heltalsvariabel gives som input.

Main.java

Main.java

copy
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));
}
}
12345678910111213141516171819202122232425262728293031
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)); } }

I dette eksempel har vi skrevet en metode, der multiplicerer den akkumulerende variabel med tal fra 1 til det angivne tal for at beregne fakultetet. Det er en ligetil tilgang, og du kan se, hvordan vi bruger denne metode flere gange i main-metoden, hvilket spar plads og forbedrer læsbarheden af koden. Dernæst bruger vi vores metode inde i System.out.println, fordi metoden returnerer en int-værdi.

Eksempel 3

Vi vil skrive en metode, der opretter en forkortelse ud fra et array af strenge.

Main.java

Main.java

copy
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));
}
}
1234567891011121314151617181920212223242526272829
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)); } }

I denne metode bruger vi klassen StringBuilder til at kalde append()-metoden og tilføje det store begyndelsesbogstav til en oprindeligt tom streng. På denne måde gennemløber vi hvert element i arrayet, tager bogstavet på den nul'te position (det første bogstav i hvert ord), konverterer det til stort med toUpperCase()-metoden og tilføjer det til vores resultat med append()-metoden. Til sidst bruger vi toString()-metoden til at konvertere vores StringBuilder til en String.

1. Hvad er en returværdi i en metode?

2. Hvad returnerer en void-metode?

3. Kan en metode bruges inde i en anden metode?

question mark

Hvad er en returværdi i en metode?

Select the correct answer

question mark

Hvad returnerer en void-metode?

Select the correct answer

question mark

Kan en metode bruges inde i en anden metode?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 5

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

We use cookies to make your experience better!
some-alt