首頁 > Java > java教程 > 主體

Java 中的 For 循環

PHPz
發布: 2024-08-30 15:24:42
原創
1139 人瀏覽過

以下文章提供了 Java 中 For 迴圈的概述。循環是Java中的一個概念,當某個條件成立時,重複執行一組語句。 Java 提供了三種執行迴圈的方法。

他們是:

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

  • For 循環
  • While 循環
  • Do while 迴圈

步驟

以下是提到的步驟:

  • 初始化條件 – 在初始化階段,我們引入Java程式中要使用的變數。一般來說,變數初始化為零或一。
  • 測試條件– 在測試條件下,檢查計數器變數之一是否大於或小於某一數量。
  • 語句執行 – 在此階段,執行 print 語句或 for 迴圈內的變量,從而更容易產生輸出。有時此階段也會使用 print 語句。
  • 遞增/遞減條件——在這個階段,循環控制變數或計數器變數通常會加1,以將程式碼向前移動。如果程式條件需要,循環控制變數也可以減 1。
  • 終止循環– 當測試條件階段條件不滿足時,循環關閉,不再工作。

Java 是一個入口控制循環,因為在執行語句之前檢查條件。

Java 程式中 for 迴圈的語法可以使用以下內容輕鬆執行。

文法:

for (initialization condition; testing condition;
increment/decrement)
{
statement(s) or print statement
}
登入後複製

流程圖:

Java 中的 For 循環

Java 中的 For 循環範例

下面給出的是提到的範例::

範例#1

在第一個範例中,我們將使用 for 迴圈在 Java 程式中產生前 10 個數字。下面給出了範例程式碼以及輸出。類別的名稱是forLoopDemo。循環語句分為三個階段。它從 1 到 10 運行,產生其間的所有自然數。

代碼:

class forLoopDemo
{
public static void main(String args[])
{
// for loop 0begins when x=1
// and runs till x <=10
System.out.println("OUTPUT OF THE FIRST 10 NATURAL NUMBERS");
for (int x = 1; x <= 10; x++)
System.out.println(+ x)
}
}
登入後複製

輸出:

Java 中的 For 循環

範例#2

第一個範例之後,我們繼續第二個範例,其中我們引入一個陣列並列印數組中的某些元素。列印數組中元素的語法如下。

文法:

for (T element:Collection obj/array)
{
statement(s)
}
登入後複製

範例程式碼以及輸出如下所示。換句話說,它也稱為增強型 for 迴圈。下面的程式碼也顯示了簡單的循環格式。

代碼:

// Java program to illustrate enhanced for loop
public class enhanced for loop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};
//enhanced for loop
for (String x:array)
{
System.out.println(x);
}
/* for loop for same function
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
登入後複製

輸出:

Java 中的 For 循環

範例#3

在範例 3 中,我們將檢查無限 for 迴圈。無限 for 迴圈就是不停頓地運行的迴圈。這是使用 for 迴圈的缺點之一。可以故意創建無限循環。在大多數情況下,無限 for 迴圈是錯誤建立的。在下面的程式碼中,由於沒有提供更新語句,因此創建了無限循環。

代碼:

//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
public static void main(String[] args)
{
// infinite loop because condition is not apt
// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
int x = 5;
// infinite loop because update statement
// is not provided.
while (x == 5)
{
System.out.println("In the loop");
}
}
}
登入後複製

輸出:

Java 中的 For 循環

上面顯示了範例輸出以及 Java 虛擬機器的運作情況。 Java虛擬機無限期地運行,並且不會停止。可以透過右鍵單擊 JVM 圖示(如圖所示)然後停止它來停止 JVM。另外,也顯示了快速鍵,即 Control + Shift + R。

範例#4

在範例 4 中,我們將看到另一個 for 迴圈應用程序,它是一個巢狀的 for 迴圈。巢狀 for 迴圈是指 for 迴圈內有一個 for 迴圈。這意味著兩個 for 迴圈彼此內部。它們通常用於在 Java 平台中列印複雜的圖案。下面顯示了巢狀 for 迴圈的範例。

這裡的類別名為 PyramidExample。然後聲明 main()。之後,宣告兩循環控制變數。一個是循環控制變數“i”,另一個是循環控制變數“j”。然後在循環控制中列印“*”。給出新行以便維持金字塔結構的給定格式。在此程式碼中,程式運行了 5 次。然而,透過增加第“i”個循環控制變數的值,我們可以確保金字塔更大。

代碼:

public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
登入後複製

Output:

Java 中的 For 循環

Example #5

In this example, we are going to see how a for loop goes through each and every element of an array and prints them.

In the below code, the class name is GFG. The package java. io .* is imported here. Also, the throws IO Exception is used at the main(), which throws and removes any exception arriving at the piece of code. The ar.length() returns the length of the array. The variable x stores the element at the “i”th position and prints it. This code is one of the easiest ways of showing how to access array elements using for loop function.

Code:

// Java program to iterate over an array
// using for loop
import java.io.*;
class GFG {
public static void main(String args[]) throws IOException
{
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int i, x;
// iterating over an array
for (i = 0; i < ar.length; i++) {
// accessing each element of array
x = ar[i];
System.out.print(x + " ");
}
}
}
登入後複製

Output:

Java 中的 For 循環

Example #6

In this example, we are going to see whether a number is a palindrome or not. In this also, a for loop is used. A palindrome number is one which when reversed, represents the same number.

Examples are 121, 1331, 4334, etc.

Code:

import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}
登入後複製

Output:

Java 中的 For 循環

Java 中的 For 循環

Conclusion – For Loop in Java

In this article, we saw how a for loop is used in many cases. The condition is checked at the beginning of the loop, and then if the condition is satisfied, then it is used in the remaining part of the loop. It is very similar to a while loop which is also an entry-controlled loop. It is in contrast to the do-while loop in which the condition is checked at the exit of the loop.

For loops are used in Java and used in C, C++, Python, and many other programming languages. Mostly they are used to print patterns in menu-driven programs to check the behavior of a number and much more.

以上是Java 中的 For 循環的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!