Java Enum - Java 中的枚舉和範例
來源:
FreeCodeCamp Java 中的 枚舉(enumeration 或簡稱
enum )是一種特殊的資料類型,包含一組預先定義的常數。通常,枚舉用於處理不需要更改的值,例如一周中的幾天、季節、顏色等。
在本文中,我們將了解如何建立
枚舉以及如何將其值指派給其他變數。我們也將學習如何在
switch語句中使用枚舉或循環遍歷其值。
如何在 Java 中建立枚舉
要建立
枚舉,我們使用enum關鍵字。
這與使用class關鍵字建立類別的方式類似。這是一個例子:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
在此程式碼中,我們建立了一個名為
Colors的枚舉。您可能會注意到這裡的所有
枚舉值都是大寫的 - 但這只是一般約定。如果數值寫成小寫,就不會出錯。
枚舉中的每個值都用逗號分隔。接下來我們將建立一個新變數並為其指派 enum 的值
之一。
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red);
}
}
這類似於初始化任何其他變數。在程式碼中,我們初始化了
Colors變量,並使用點語法為其分配了
枚舉值之一:
Colors red = Colors.RED; 。
請注意,我們可以在Main類別中建立枚舉,並且程式碼仍然有效:
public class Main {
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red);
}
}
如果我們想要取得任何值的序數,我們必須使用
ordinal()方法。這是另一個例子:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red.ordinal());
}
}
上述程式碼中的
red.ordinal()回傳 0。
如何在 Switch 語句中使用 Enum
現在我們將學習如何在
switch語句中使用
枚舉:
public class Main {
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public static void main(String[] args) {
Colors myColor = Colors.YELLOW;
switch(myColor) {
case RED:
System.out.println("The color is red");
break;
case BLUE:
System.out.println("The color is blue");
break;
case YELLOW:
System.out.println("The color is yellow");
break;
case GREEN:
System.out.println("The color is green");
break;
}
}
}
這是一個非常簡單的範例,說明如何在
switch語句中 使用
枚舉。我們可以向控制台輸出
「The color is Yellow」 ,因為這是唯一符合switch語句條件的情況。
如何循環遍歷枚舉值
對於枚舉,Java有一個
values()方法,它會傳回一個枚舉值陣列。我們將使用
foreach循環來迭代並列印 enum 的
值。你可以這樣做:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
for (Colors allColors : Colors.values()) {
System.out.println(allColors);
}
}
}
結論
在本文中,我們了解了Java 中的
枚舉是什麼、如何建立枚舉以及如何將其值指派給其他變數。我們也了解如何將
枚舉類型與
switch語句一起使用,以及如何循環遍歷
枚舉值。快樂編碼!
Java 中的 While 迴圈:語法與用途
來源:
Dev.to今天我們將了解 Java 中while循環 的概念和語法,並了解如何使用此循環來迭代數組。
While 迴圈概念
while循環是 Java 中的基本循環類型之一,可在程式中用於多種用途。
與for迴圈一樣,
while迴圈可用於根據條件執行操作。在
while循環中,計數器並不總是打開。
while循環的迭代次數取決於循環條件回傳
true的頻率。
與for迴圈不同,在大多數情況下, while迴圈中的初始化是可選的。有時,
while循環並不總是在循環中執行。讓我們舉一個具體的例子:
System.out.println("You Input a wrong number");
int i = input.nextInt();
while(i==1||i==2||i==3||i==4){
System.out.println("inside the while loop block");
}
System.out.println("outside the while loop block")
這裡的程式碼使用
while循環根據某些條件驗證使用者輸入,因此僅重複一次。
While 迴圈語法
while(condition){
}
while 循環條件採用一個傳回布林值
true或
false 的參數。當
true時,執行
while循環中的程式碼,當
false時,循環結束。
每個while循環的流程
while迴圈有一個可接受的流程:初始化 > 條件 > 語句執行。第一階段是初始化階段。它可以透過聲明變數並初始化它來完成。第二階段是條件階段,該階段必須傳回
true或
false。如果傳回
true ,則執行
while循環中的語句,如果傳回
false,則循環結束。
使用 while 迴圈作為計數器
與
for迴圈一樣,
while迴圈也可以用作計數器。下面的程式使用
while循環從 2 迭代到 20。這是為了列印偶數。
int j = 2;
while(j <=20){
System.out.println(j);
j+=2;
}
可以看到,在程式中,
j被初始化為 2,如果j小於或等於 20,則測試條件。如果傳回
true,則執行該語句,如果傳回
false,則
while迴圈結束。
while 迴圈可用於迭代數組
int[] age = {20, 30, 40, 40, 90};
int i = 0;
while (i < age.length)
{
System.out.println(age[i]);
i++;
}
在此程式碼中,我們有一個年齡數組,並使用
while循環來迭代該數組並列印出數組中的每個元素。為了檢查數組中元素的總數,使用了
age.length,在上面的程式中
i作為索引。
while 迴圈中的 Break 語句
Break語句也可以用在
while迴圈中,就像
for迴圈一樣:
int i = 1;
while (true)
{
System.out.println(i);
if (i == 20)
{
break;
}
i++;
}
在上面的程式中,
break語句用於無限期地停止程式執行。
While(true)意味著程式將始終傳回
true。
while循環可用於驗證使用者輸入
System.out.println("Select an option\n"+
"1.Add Users\n"+
"2.Delete Users");
int x = input.nextInt();
while(x==1||x==2){
}
System.out.println("You Input a wrong number");
在上面的程式中,使用
while循環來檢查使用者的輸入並確保使用者選擇 1 或 2。如果使用者選擇不同的數字,則
System.out.println("您輸入了錯誤的數字"); 。
帶有 while 迴圈的條件語句
int i = 0;
while(i<10){
i++;
if(i==5){
continue;
} System.out.println(i);
}
條件語句也可以用在
while迴圈中來跳過特定的迭代。在上面的程式中,
if語句用於檢查
i==5,如果它傳回
true則將跳過該特定迭代。
while循環設計
讓我們使用
while循環創建一個猜謎遊戲。
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
static boolean hasWon;
static int count;
static int guess;
public static void main (String[] args)
{
System.out.println("Welcome to guess world");
System.out.println("Do you want to start the game? ");
System.out.println("1.Yes\n" +
"2.No");
int option= input.nextInt();
int guessNumber = (int) Math.floor(Math.random() * 10 + 1);
if (!( option == 2 ))
{
System.out.println("Welcome, choose a guess between 1 and 10\n" +
"you have only ten trials");
while (count <= 10)
{
int userGuess = input.nextInt();
if (userGuess == guessNumber)
{
hasWon = true;
System.out.println("Congratulation, you guessed right at " + count + " count");
count++;
break;
}
else if (userGuess < guessNumber)
{
hasWon = false;
System.out.println("Oops, you guessed a lower number, try an higher one");
count++;
}
else if (userGuess > guessNumber)
{
System.out.println("Oops, you guessed an high number, try an lower one");
hasWon = false;
}
}
if (hasWon == false)
{
System.out.println("You trials exceeds 10");
}
}
}
}
在此程式中,我們使用while循環 創建一個猜數字遊戲。玩家只有 10 次嘗試機會。一旦他玩遊戲的次數超過10次,遊戲就結束。如果玩家猜對了正確的數字,控制台上會顯示一則祝賀訊息。
結論
while循環看起來很複雜,但要掌握起來並不難。它也是 Java 中第二常用的循環,可用於多種目的。
GO TO FULL VERSION