Program pisanan kita yaiku urutan instruksi sing dieksekusi siji-sijine. Ora ana garpu. Iki kalebu HelloWorld, sing nampilake salam. Iku kalebu petungan aritmetika. Sawise program pisanan, kita sinau babagan cabang, yaiku carane nggawe program nindakake tumindak sing beda-beda gumantung saka kahanan tartamtu. Ing ngisor iki kode kanggo ngontrol pemanasan pusat lan sistem AC:
terus.
if (tempRoom>tempComfort)
airConditionerOn();
if (tempRoom<tempComfort)
heaterOn();
Njupuk langkah sabanjure. Ing saben dinten, kita asring nindakake tumindak repetitive seragam, contone, peeling apel kanggo pai. Proses menarik iki bisa diterangake minangka:
-
Yen ana apel ing mangkuk, banjur tindakake langkah 1.1 nganti 1.4:
- 1.1. Jupuk apel
- 1.2. Peel lan Cut menyang irisan-irisan
- 1.3. Susun irisan apel ing kerak pai ing panci
- 1.4. Bali menyang langkah 1.
- We dasi dhéwé kanggo nomer apel, nanging yen kita ora duwe cukup, banjur sawetara printah bakal kaleksanan tanpa "payload" (lan kita bisa Cut dhéwé nalika nyoba kanggo pil apel nonexistent).
- Yen ana luwih akeh apel tinimbang prentah kanggo dikupas, mula sawetara apel ora dikupas.
- Kode kuwi angel diwaca. Wis akeh pengulangan lan angel diowahi.
Loops minangka statement sing ngidini tumindak bisa ditindakake bola-bali
Loop nalika Jawa bakal bisa digunakake kanthi apik. Konstruksi iki ndadekake pirang-pirang tumindak dadi struktur sing ringkes lan bisa dingerteni. Nggunakake loop sementara , algoritma ngiris apel kanggo pai bisa katon kaya iki ing Jawa:
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.");
Sintaks printah
Varian pisanan saka statement while kaya iki:
while (Boolean expression) {
// Loop body — the statement(s) that are repeatedly executed
}
Mangkene panjelasan langkah-langkah babagan apa sing kedadeyan nalika kode iki dieksekusi:
- Kita ngevaluasi ekspresi Boolean sing ditemokake ing kurung sawise tembung kunci nalika .
- Yen ekspresi Boolean dievaluasi dadi bener, pratelan ing awak loop bakal dieksekusi. Sawise statement pungkasan ing awak loop dieksekusi, banjur pindhah menyang langkah 1
- Yen ekspresi Boolean dievaluasi dadi palsu, banjur pindhah menyang statement pisanan sawise loop while .
Loop karo prasyarat
Amarga kita tansah ngevaluasi ekspresi Boolean (kahanan kanggo ngetik loop) sadurunge nglakokake awak loop, wangun while loop iki asring diarani loop kanthi precondition . Ayo nggawe tabel saka sepuluh kakuwasan pisanan saka nomer:
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++;
}
}
Output konsol:
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
Loop karo postcondition
Mangkene varian kapindho loop iki:
do {
// Loop body — the statement(s) that are repeatedly executed
} while (Boolean expression);
Mangkene panjelasan apa sing kedadeyan nalika kode iki dieksekusi:
- Badan loop dieksekusi (sanalika sawise tembung kunci do ).
- Kita ngevaluasi ekspresi Boolean sing ditemokake ing kurung sawise tembung kunci nalika .
- Yen ekspresi Boolean dievaluasi dadi bener, banjur pindhah menyang langkah 1
- Yen ekspresi Boolean dievaluasi dadi palsu, banjur pindhah menyang statement pisanan sawise loop while .
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
}
Output konsol:
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
Pay manungsa waé kanggo owah-owahan ing kode. Bandingake iki karo loop karo prasyarat.
Kasunyatan sing menarik babagan nggarap puteran
Cabang statement ing awak loop
Ana rong statement sing mengaruhi eksekusi sajrone loop: break (sing bakal kita bahas kanthi luwih rinci ing bab sabanjure) lan- terus - skips eksekusi liyane saka awak daur ulang ing pengulangan saiki lan mlumpat menyang evaluasi nalika statement Boolean expression. Yen ekspresi kasebut dievaluasi dadi bener, banjur loop terus.
- break - langsung mungkasi eksekusi pengulangan saiki lan transfer kontrol menyang statement pisanan sawise daur ulang. Mangkono, statement iki mungkasi eksekusi loop saiki. Kita bakal nimbang luwih rinci ing artikel sabanjure.
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());
}
Continue statement asring digunakake nalika statement ing awak loop kudu dieksekusi yen kondisi tartamtu wis wareg
. Contone, kita bisa uga pengin nindakake tumindak nalika sensor hardware wis micu (yen ora, mung terus daur ulang kang kita maca sensor) utawa kita bisa uga pengin ngetung ekspresi mung ing iterasi tartamtu saka daur ulang. Conto kasus terakhir bisa dideleng nalika kita nggunakake loop while kanggo ngetung jumlah kubus saka nomer alam sing kothak kurang saka nomer nomer. Bingung? Priksa kode ing ngisor iki:
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
}
Gelung tanpa wates
Pernyataan percabangan iki asring digunakake ing puteran tanpa wates. Kita nelpon loop tanpa wates yen kondisi Boolean kanggo metu saka loop ora tau wareg. Ing kode, katon kaya iki:
while (true) {
// Loop body
}
Ing kasus iki, statement
break mbantu kita metu saka daur ulang. Jinis daur ulang iki cocok nalika nunggu kondisi njaba sing ditemtokake ing njaba awak daur ulang. Contone, ing sistem operasi utawa game (metu saka daur ulang tegese metu saka game). Utawa nalika nggunakake algoritma sing nyoba, kanthi saben pengulangan daur ulang, kanggo nambah sawetara asil, nanging mbatesi jumlah pengulangan adhedhasar wektu sing wis liwati utawa kedadeyan saka acara eksternal (contone, checkers, catur, utawa prakiraan cuaca). Elinga yen ing kahanan normal puteran tanpa wates ora dikarepake. Kanggo nduduhake, ayo bali menyang eksponensial:
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
}
}
Output konsol:
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
Sarang puteran
Lan saiki kita teka menyang topik pungkasan babagan puteran. Elinga pai apel kasebut (muga-muga sampeyan ora keluwen saiki) lan loop peeling apel:-
Yen ana apel ing mangkuk, banjur tindakake langkah 1.1 nganti 1.4:
- 1.1. Jupuk apel
- 1.2. Peel lan Cut menyang irisan-irisan
- 1.3. Susun irisan apel ing kerak pai ing panci
- 1.4. Bali menyang langkah 1.
- Jumlah irisan = 0
-
Anggere jumlah irisan <12, banjur tindakake langkah 2.1 kanggo 2.3
- 2.1. Cut irisan liyane saka apel
- 2.2. Jumlah irisan ++
- 2.3. Bali menyang langkah 2
-
Yen ana apel ing mangkuk, banjur kita tindakake langkah 1.1 nganti 1.6:
- 1.1. Jupuk apel
- 1.2. Peel iku
- 1.3. Jumlah irisan = 0
- 1.4. Anggere jumlah irisan < 12, banjur tindakake langkah 1.4.1 nganti 1.4.3
- 1.4.1. Cut irisan liyane saka apel
- 1.4.2. Jumlah irisan ++ 1.4.3. Bali menyang langkah 1.4
- 1.5. Susun irisan apel ing kerak pai ing panci
- 1.6. Bali menyang langkah 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)"
}
Output konsol:
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
Loops (utamane, statement
while ) minangka salah sawijining pamblokiran dhasar piranti lunak. Kanthi ngrampungake tugas ing CodeGym, sampeyan bakal sinau kabeh macem-macem puteran, ngerti seluk-beluke, lan entuk katrampilan praktis kanggo nggunakake.
GO TO FULL VERSION