Våra allra första program var en sekvens av instruktioner som exekveras en efter en. Inga gafflar. Detta inkluderar HelloWorld, som visar en hälsning. Det inkluderar aritmetiska beräkningar. Efter våra första program lärde vi oss hur man förgrenar sig, dvs hur man får ett program att utföra olika åtgärder beroende på specifika förutsättningar. Här är koden för att styra ett centralvärme- och luftkonditioneringssystem:
Fortsätta.
if (tempRoom>tempComfort)
airConditionerOn();
if (tempRoom<tempComfort)
heaterOn();
Ta nästa steg. I vardagen utför vi ofta enhetliga repetitiva åtgärder, till exempel att skala äpplen till en paj. Denna fascinerande process kan beskrivas som:
-
Om det finns äpplen i skålen, utför vi steg 1.1 till 1.4:
- 1.1. Ta ett äpple
- 1.2. Skala den och skär den i skivor
- 1.3. Lägg äppelskivorna i pajskalet i en panna
- 1.4. Gå tillbaka till steg 1.
- Vi binder oss till antalet äpplen, men om vi inte har tillräckligt med dem, så kommer en del av kommandona att utföras utan "nyttolast" (och vi kan skära oss när vi försöker skala ett obefintligt äpple).
- Om det finns fler äpplen än kommandon att skala, skulle en del av äpplena lämnas oskalade.
- Sådan kod är svår att läsa. Den har många repetitioner och är svår att modifiera.
Slingor är påståenden som gör att åtgärder kan utföras upprepade gånger
Javas while loop kommer att fungera bra i vårt fall. Denna konstruktion sätter flera åtgärder i en kortfattad och begriplig struktur. Med hjälp av en while -loop kan en äppelskivningsalgoritm för en paj se ut så här i Java:while (numberOfApplesInBowl > 0) {
apple = bowl.grabNextApple();
arrangeInPie(apple.peel().slice());
numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
}
System.out.println("The apples for the pie have been processed.");
Kommandosyntax
Den första varianten av while -satsen är så här:while (Boolean expression) {
// Loop body — the statement(s) that are repeatedly executed
}
Här är en steg-för-steg förklaring av vad som händer när den här koden exekveras:
- Vi utvärderar det booleska uttrycket som finns inom parentes efter nyckelordet while .
- Om det booleska uttrycket evalueras till sant, exekveras satserna i loopkroppen . Efter att den sista satsen i loopkroppen har körts går vi till steg 1
- Om det booleska uttrycket utvärderas till falskt, så hoppar vi till den första satsen efter while- loopen.
Slinga med en förutsättning
Eftersom vi alltid utvärderar det booleska uttrycket (villkoret för att gå in i loopen) innan vi exekverar loopkroppen, kallas denna form av while -loopen ofta för en loop med en precondition . Låt oss bygga en tabell över de första tio potenserna av ett tal:public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = 1; // The result of exponentiation
int exponent = 1; // The initial exponent
while (exponent <= 10) { // The condition for entering the loop
result = result * base;
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
}
}
Konsolutgång:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0
Slinga med postcondition
Här är den andra varianten av denna loop:do {
// Loop body — the statement(s) that are repeatedly executed
} while (Boolean expression);
Här är en förklaring av vad som händer när den här koden körs:
- Loppen exekveras (direkt efter do nyckelordet).
- Vi utvärderar det booleska uttrycket som finns inom parentes efter nyckelordet while .
- Om det booleska uttrycket utvärderas till sant, går vi till steg 1
- Om det booleska uttrycket utvärderas till falskt, så hoppar vi till den första satsen efter while- loopen.
public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = base; // The result of exponentiation
int exponent = 1; // The initial exponent
do {
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
result = result * base;
} while (result < 10000); // The condition for exiting the loop
}
Konsolutgång:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
Process finished with exit code 0
Var uppmärksam på ändringarna i koden. Jämför detta med slingan med en förutsättning.
Intressanta fakta om att arbeta med loopar
Förgreningssatser inom loopkroppen
Det finns två påståenden som påverkar exekveringen inom en loop: break (som vi kommer att diskutera mer i detalj i nästa kapitel) och- continue — hoppar över exekveringen av resten av loopkroppen i den aktuella iterationen och hoppar till utvärderingen av while-satsens booleska uttryck. Om uttrycket evalueras till sant fortsätter loopen.
- break — avslutar omedelbart exekveringen av den aktuella iterationen och överför kontrollen till den första satsen efter loopen. Således avslutar denna sats exekveringen av den aktuella slingan. Vi kommer att överväga det mer i detalj i nästa artikel.
while (numberOfApplesInBowl > 0) {
apple = bowl.grabNextApple();
numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
if (apple.isBad()) { // This method returns true for rotten apples
apple.throwInGarbage();
continue; // Continue the loop. Jump to evaluation of numberOfApplesInBowl > 0
}
arrangeInPie(apple.peel().slice());
}
Fortsätt -satsen används ofta när satser i loopkroppen behöver köras om ett visst villkor är uppfyllt
. Till exempel kan vi vilja utföra åtgärder när en hårdvarusensor triggas (annars fortsätter du helt enkelt slingan där vi tar sensoravläsningar) eller så vill vi kanske bara beräkna ett uttryck på vissa iterationer av en loop. Ett exempel på det senare fallet kan ses i vår användning av en while-loop för att beräkna summan av kuber av naturliga tal vars kvadrat är mindre än antalet tal. Förvirrad? Kolla in följande kod:
public static void main(String[] args) {
int sum = 0; // Total amount
int i = 0; // Initial number in the series
int count = 20; // Number of numbers
while (i <= count) {
i++; // Get the next number — "i++" is equivalent to "i = i + 1"
if (i * i <= count) // If the square of the number is less than
continue; // the number of numbers, then we won't calculate the sum
// Jump to the next number in the loop
sum += i * i * i; // Otherwise, we calculate the sum of the cubes of numbers
} // "sum += i * i * i" is notation that is equivalent to "sum = sum + i * i * i"
System.out.println(sum); // Print the result
}
Oändlig loop
Dessa förgreningssatser används oftast i oändliga loopar. Vi kallar en slinga oändlig om det booleska villkoret för att lämna slingan aldrig är uppfyllt. I koden ser det ut ungefär så här:while (true) {
// Loop body
}
I det här fallet hjälper en
break -sats oss att lämna loopen. Denna typ av slinga är lämplig när man väntar på yttre förhållanden som bestäms utanför slingans kropp. Till exempel i operativsystem eller spel (att lämna loopen innebär att lämna spelet). Eller när man använder algoritmer som försöker, med varje iteration av en loop, att förbättra ett resultat, men begränsar antalet iterationer baserat på förfluten tid eller förekomsten av en extern händelse (t.ex. pjäs, schack eller väderprognoser). Kom ihåg att under normala förhållanden är oändliga slingor inte önskvärda. För att demonstrera, låt oss återgå till exponentieringen:
public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = 1; // The result of exponentiation
int exponent = 1; // The initial exponent
while (true) {
result = result * base;
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
if (exponent > 10)
break; // Exit the loop
}
}
Konsolutgång:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0
Kapslade slingor
Och nu kommer vi till vårt sista ämne om loopar. Kom ihåg den där äppelpajen (jag hoppas att du inte är hungrig just nu) och vår äppelskalningsögla:-
Om det finns äpplen i skålen, utför vi steg 1.1 till 1.4:
- 1.1. Ta ett äpple
- 1.2. Skala den och skär den i skivor
- 1.3. Lägg äppelskivorna i pajskalet i en panna
- 1.4. Gå tillbaka till steg 1.
- Antal skivor = 0
-
Så länge antalet skivor är < 12, utför sedan steg 2.1 till 2.3
- 2.1. Skär en skiva till av äpplet
- 2.2. Antal skivor++
- 2.3. Gå tillbaka till steg 2
-
Om det finns äpplen i skålen, utför vi steg 1.1 till 1.6:
- 1.1. Ta ett äpple
- 1.2. Skala den
- 1.3. Antal skivor = 0
- 1.4. Så länge antalet skivor är < 12, utför sedan steg 1.4.1 till 1.4.3
- 1.4.1. Skär en skiva till av äpplet
- 1.4.2. Antal skivor++ 1.4.3. Återgå till steg 1.4
- 1.5. Lägg äppelskivorna i pajskalet i en panna
- 1.6. Gå tillbaka till steg 1.
public static void main(String[] args) {
// Print the second factors in a row
System.out.println(" 2 3 4 5 6 7 8 9");
int i = 2; // Assign the first factor to the variable
while (i < 10) { // First loop: execute as long as the first factor is less than 10
System.out.print(i + " | "); // Print the first factor at the beginning of the line
int j = 2; // The starting value of the second factor
while (j < 10) { // Second loop: execute as long as the second factor is less than 10
int product = i * j; // Calculate the product of the factors
if (product < 10) // If the product is a single digit, then we print two spaces after the product
System.out.print(product + " ");
else // Otherwise, print the product and one space after it
System.out.print(product + " ");
j++; // Increment the second factor by one
} // Go to the beginning of the second loop, i.e. "while (j < 10)"
System.out.println(); // Move to the next line on the console
i++; // Increment the first factor by one
} // Go to the beginning of the first loop, i.e. "while (i < 10)"
}
Konsolutgång:
2 3 4 5 6 7 8 9
2 | 4 6 8 10 12 14 16 18
3 | 6 9 12 15 18 21 24 27
4 | 8 12 16 20 24 28 32 36
5 | 10 15 20 25 30 35 40 45
6 | 12 18 24 30 36 42 48 54
7 | 14 21 28 35 42 49 56 63
8 | 16 24 32 40 48 56 64 72
9 | 18 27 36 45 54 63 72 81
Process finished with exit code 0
Slingor (i synnerhet
while -satsen) är en av de grundläggande byggstenarna i programvara. Genom att lösa uppgifter på CodeGym kommer du att lära dig alla olika typer av loopar, förstå deras krångligheter och få praktiska färdigheter i att använda dem.