วนสลับหรือหยุดพัก? การตัดสินใจและทำซ้ำด้วยคำสั่ง Java
แอ็พพลิเคชัน Java ประเมินนิพจน์ในบริบทของคำสั่งซึ่งใช้สำหรับงานเช่นการประกาศตัวแปรการตัดสินใจหรือการทำซ้ำบนคำสั่ง คำสั่งสามารถแสดงเป็นคำสั่งธรรมดาหรือคำสั่งประกอบ:
- คำสั่งง่ายๆคือการเรียนการสอนแบบสแตนด์อโลนเดียวสำหรับการดำเนินงาน; ต้องปิดท้ายด้วยอักขระอัฒภาค (
;
) - งบสารประกอบเป็นลำดับของง่ายและงบสารประกอบอื่น ๆ ที่อยู่ระหว่างตัวละครเปิดโล่งและใกล้รั้ง (ก
{
และ}
) ซึ่งคั่นขอบเขตคำสั่งสารประกอบของ งบ Compound สามารถเป็นที่ว่างเปล่าจะปรากฏขึ้นที่ใดก็ตามที่งบง่ายปรากฏขึ้นและเป็นที่รู้จักกันผลัดกันเป็นบล็อกคำสั่งผสมไม่ได้จบลงด้วยอัฒภาค
ในบทช่วยสอนนี้คุณจะได้เรียนรู้วิธีใช้คำสั่งในโปรแกรม Java ของคุณ คุณสามารถใช้งบเช่นif
, if-else
, switch
, for
และwhile
ตัวแปรประกาศและระบุการแสดงออกในการตัดสินใจทำ, สำทับ (หรือห่วง) มากกว่างบทำลายและยังคงย้ำและอื่น ๆ ฉันจะทิ้งคำสั่งที่แปลกใหม่กว่านี้ไว้บางส่วนเช่นคำสั่งสำหรับการส่งคืนค่าจากวิธีการที่เรียกและสำหรับการทิ้งข้อยกเว้นสำหรับบทเรียน Java 101 ในอนาคต
สลับนิพจน์ใน Java 12
โปรดทราบว่าบทช่วยสอนนี้ได้รับการอัปเดตสำหรับ Java 12 และมีคำแนะนำสั้น ๆ เกี่ยวกับswitch
นิพจน์
การประกาศตัวแปรและการกำหนด
ฉันเคยแนะนำตัวแปร Java ไปก่อนหน้านี้และอธิบายว่าต้องประกาศก่อนที่จะใช้ เนื่องจากการประกาศตัวแปรเป็นเกาะของรหัสแบบสแตนด์อโลนจึงเป็นคำสั่งที่มีประสิทธิภาพซึ่งเป็นคำสั่งง่ายๆที่แน่นอน ทั้งหมดนี้เป็นคำสั่งประกาศตัวแปร:
int age = 25; float interest_rate; char[] text = { 'J', 'a', 'v', 'a' }; String name;
การประกาศตัวแปรน้อยที่สุดประกอบด้วยชื่อประเภทตามด้วยลำดับของคู่วงเล็บเหลี่ยมตามด้วยชื่อตามด้วยลำดับของคู่วงเล็บเหลี่ยมและปิดท้ายด้วยอัฒภาค ตัวแปรอาจถูกกำหนดค่าเริ่มต้นอย่างชัดเจนในระหว่างการประกาศ
ตอนนี้ให้พิจารณาคำสั่งมอบหมายซึ่งเกี่ยวข้องอย่างใกล้ชิดกับคำสั่งการประกาศตัวแปร คำสั่งมอบหมายกำหนดค่า (อาจเป็นการอ้างอิงอาร์เรย์หรือการอ้างอิงถึงวัตถุ) ให้กับตัวแปร นี่คือตัวอย่างบางส่วน:
age = 30; interest_rate = 4.0F; age += 10; text[1] = 'A'; text[2] = 'V'; text[3] = 'A'; name = "John Doe";
คำสั่งมอบหมายเป็นตัวอย่างของคำสั่งนิพจน์ซึ่งเป็นนิพจน์ที่อาจใช้เป็นคำสั่งได้หากตามด้วยอัฒภาค นิพจน์ต่อไปนี้มีคุณสมบัติเป็นคำสั่งนิพจน์:
- Preincrement (เช่น
++x;
) - Predecrement (เช่น
--y;
) - Postincrement (เช่น
x++;
) - Postdecrement (เช่น
y--;
) - วิธีการโทร (เช่น
System.out.println("Hello");
) - การสร้างวัตถุ (เช่น
new String("ABC");
)
การประกาศตัวแปรด้วย jshell
คุณสามารถใช้jshell
เพื่อทดลองกับการประกาศตัวแปรและคำสั่งนิพจน์ นี่คือตัวอย่างบางส่วนที่จะช่วยให้คุณเริ่มต้นได้ (ดู "เรียนรู้ Java ตั้งแต่เริ่มต้น" สำหรับข้อมูลเบื้องต้นเกี่ยวกับ Java Shell):
jshell> int age = 25 age ==> 25 jshell> float interest_rate interest_rate ==> 0.0 jshell> char[] text = { 'J', 'a', 'v', 'a' } text ==> char[4] { 'J', 'a', 'v', 'a' } jshell> String name name ==> null jshell> age = 30 age ==> 30 jshell> interest_rate = 4.0F interest_rate ==> 4.0 jshell> age += 10 $7 ==> 40 jshell> text[1] = 'A' $8 ==> 'A' jshell> text[2] = 'V' $9 ==> 'V' jshell> text[3] = 'A' $10 ==> 'A' jshell> name = "John Doe" name ==> "John Doe" jshell> text text ==> char[4] { 'J', 'A', 'V', 'A' } jshell> age++ $13 ==> 40 jshell> age age ==> 41
สังเกตว่าage++
ดูเหมือนจะไม่สำเร็จอะไรเลย ที่นี่คุณจะเห็นว่าได้รับมอบหมายให้กับตัวแปรรอยขีดข่วน40
$13
อย่างไรก็ตามตัวดำเนินการ postincrement จะดำเนินการส่วนเพิ่มหลังจากส่งคืนค่าปัจจุบัน (อันที่จริงมันเก็บค่าปัจจุบันไว้ที่ใดที่หนึ่งทำการเพิ่มแล้วส่งกลับค่าที่เก็บไว้) การป้อนอายุพิสูจน์ว่าage
มี 41 ซึ่งเป็นผลจากการดำเนินการหลัง
Java Shell จัดเตรียมคำสั่งและคุณลักษณะต่างๆที่ช่วยให้การทำงานกับส่วนย่อยง่ายขึ้น ตัวอย่างเช่น/list
คำสั่งจะแสดงข้อมูลโค้ดทั้งหมดที่ป้อนในเซสชันปัจจุบัน:
jshell> /list 1 : int age = 25; 2 : float interest_rate; 3 : char[] text = { 'J', 'a', 'v', 'a' }; 4 : String name; 5 : age = 30 6 : interest_rate = 4.0F 7 : age += 10 8 : text[1] = 'A' 9 : text[2] = 'V' 10 : text[3] = 'A' 11 : name = "John Doe" 12 : text 13 : age++ 14 : age
ตัวเลขในคอลัมน์ด้านซ้ายจะระบุข้อมูลโค้ดโดยไม่ซ้ำกัน คุณสามารถใช้หมายเลขนี้เพื่อเรียกใช้ข้อมูลโค้ดอีกครั้งแสดงรายการข้อมูลโค้ดปล่อย (ลบ) ข้อมูลโค้ดและอื่น ๆ :
jshell> /12 text text ==> char[4] { 'J', 'A', 'V', 'A' } jshell> /list 13 13 : age++ jshell> /drop 7 | dropped variable $7 jshell> /list 1 : int age = 25; 2 : float interest_rate; 3 : char[] text = { 'J', 'a', 'v', 'a' }; 4 : String name; 5 : age = 30 6 : interest_rate = 4.0F 8 : text[1] = 'A' 9 : text[2] = 'V' 10 : text[3] = 'A' 11 : name = "John Doe" 12 : text 13 : age++ 14 : age 15 : text
ที่นี่เราได้ป้อน/ 12เพื่อเรียกใช้ข้อมูลโค้ด # 12 อีกครั้งซึ่งแสดงเนื้อหาของไฟล์text
. จากนั้นเราจะป้อน/ รายการ 13ไปยังรายการ snippet # 13 age
ซึ่งเพิ่มขึ้น ต่อไปเราป้อน/ วาง 7เพื่อลบข้อมูลโค้ด # 7 (ไม่มีage += 10
ข้อมูลโค้ดอีกต่อไป) ในที่สุดเราก็ป้อน/ listเพื่อแสดงรายการข้อมูลโค้ดทั้งหมดอีกครั้ง โปรดสังเกตว่า snippet # 7 ถูกลบออกและมีการเพิ่ม snippet # 15 ด้วย/12
คำสั่ง
การตัดสินใจ: if, if-else และเปลี่ยน
คำสั่งการตัดสินใจช่วยให้แอปพลิเคชันเลือกระหว่างเส้นทางการดำเนินการหลาย ๆ ตัวอย่างเช่นหากพนักงานขายขายสินค้าได้มากกว่า 500 รายการในเดือนนี้ให้โบนัสแก่พนักงานขาย นอกจากนี้หากคะแนนของนักเรียนในการทดสอบพีชคณิตมากกว่า 85 เปอร์เซ็นต์ขอแสดงความยินดีกับนักเรียนที่ทำได้ดี มิฉะนั้นแนะนำให้นักเรียนเรียนหนักขึ้นสำหรับการทดสอบครั้งต่อไป
Java สนับสนุนif
, if-else
และswitch
งบการตัดสินใจ นอกจากนี้switch
ยังเพิ่มคุณลักษณะนิพจน์ใหม่ใน Java 12
คำสั่ง if
คำสั่งการตัดสินใจที่ง่ายที่สุดของ Java คือif
คำสั่งซึ่งประเมินนิพจน์บูลีนและรันคำสั่งอื่นเมื่อนิพจน์นี้ประเมินว่าเป็นจริง if
คำสั่งมีไวยากรณ์ต่อไปนี้:
if (Boolean expression) statement
if
คำสั่งเริ่มต้นด้วยคำสงวนif
และยังคงมีนิพจน์บูลีนวงเล็บซึ่งจะตามมาด้วยคำสั่งที่จะดำเนินการเมื่อมีการประเมินนิพจน์บูลีนจริง
ตัวอย่างต่อไปนี้แสดงให้เห็นถึงif
คำสั่ง เมื่อage
ตัวแปรมีค่า 55 ขึ้นไปให้if
ดำเนินการSystem.out.println(...);
เพื่อส่งออกข้อความ:
if (age >= 55) System.out.println("You are or were eligible for early retirement.");
หลายคนชอบที่จะสรุปคำสั่งง่ายๆที่เป็นไปตามif
คำสั่งในวงเล็บปีกกาโดยแปลงเป็นคำสั่งประกอบที่เทียบเท่าได้อย่างมีประสิทธิภาพ:
if (age >= 55) { System.out.println("You are or were eligible for early retirement."); }
แม้ว่าการจัดฟันจะชี้แจงสิ่งที่กำลังดำเนินการโดยif
คำสั่ง แต่ฉันเชื่อว่าการเยื้องให้ความชัดเจนนี้และการจัดฟันนั้นไม่จำเป็น
การทดลองกับ if statement
Let's try out this example usingjshell
. Restart jshell
and then introduce an age
variable (of type int
) that's initialized to 55
:
jshell> int age = 55
Next, enter the first example if
statement (without the curly braces surrounding its body):
jshell> if (age >= 55) ...> System.out.println("You are or were eligible for early retirement."); You are or were eligible for early retirement. jshell>
Notice that the jshell>
prompt changes to the ...>
continuation prompt when you enter a multiline snippet. Pressing Enter after the last snippet line causes jshell
to immediately execute the snippet.
Execute /list to list all snippets. I observe that the if
statement snippet has been assigned 2
in my session. Executing /2 causes jshell
to list and then execute this snippet, and the same message is output.
Now, suppose you assign 25
to age
and then re-execute /2 (or the equivalent snippet number in your session). This time, you should not observe the message in the output.
The if-else statement
The if-else
statement evaluates a Boolean expression and executes a statement. The statement executed depends on whether the expression evaluates to true or false. Here's the syntax for the if-else
statement:
if (Boolean expression) statement1 else statement2
The if-else
statement is similar to the if
statement, but it includes the reserved word else
, followed by a statement to execute when the Boolean expression is false.
The following example demonstrates an if-else
statement that tells someone who is less than 55 years old how many years are left until early retirement:
if (age >= 55) System.out.println("You are or were eligible for early retirement."); else System.out.println("You have " + (55 - age) + " years to go until early retirement.");
Conditional operator vs if-else
The conditional operator (?:
) is similar to an if-else
statement. However, this operator cannot be used to execute alternate statements. Instead, it can only return one of two values of the same type. (The conditional operator is also sometimes known as the ternary operator.)
Chaining if-else statements
Java lets you chain multiple if-else
statements together for situations where you need to choose one of multiple statements to execute:
if (Boolean expression1) statement1 else if (Boolean expression2) statement2 else ... else statementN
Chaining works by executing a subsequent if-else
statement whenever the current if
statement's Boolean expression evaluates to false. Consider a demonstration:
if (temperature 100.0) System.out.println("boiling"); else System.out.println("normal");
The first if-else
statement determines if temperature
's value is negative. If so, it executes System.out.println("freezing");
. If not, it executes a second if-else
statement.
The second if-else
statement determines if temperature
's value is greater than 100. If so, it executes System.out.println("boiling");
. Otherwise, it executes System.out.println("normal");
.
The dangling-else problem
When if
and if-else
are used together, and the source code isn't properly indented, it can be difficult to determine which if
associates with the else
. You can see the problem in the code below:
int x = 0; int y = 2; if (x > 0) if (y > 0) System.out.println("x > 0 and y > 0"); else System.out.println("x <= 0");
You would probably expect to see x <= 0
as the output from this code, but it will never happen; instead, nothing will output. The problem is that the else
matches up to its nearest if
, which is if (y > 0)
. Reformatting the code makes it clearer what is happening:
int x = 0; int y = 2; if (x > 0) if (y > 0) System.out.println("x > 0 and y > 0"); else System.out.println("x <= 0");
Here it's clearer than an if (y > 0) ... else ...
if-else
statement follows the if (x > 0)
statement. To match the intent of the previous example, you need to introduce brace characters around if (y > 0)
and its subsequent statement. Essentially, a block will follow if (x > 0)
:
int x = 0; int y = 2; if (x > 0) { if (y > 0) System.out.println("x > 0 and y > 0"); } else System.out.println("x <= 0");
Because x > 0
evaluates to false, System.out.println("x <= 0");
executes. The else
reserved word clearly matches up to if (x > 0)
.
The switch statement
When you need to choose between several execution paths, the switch
statement offers a more efficient alternative to chaining. Have a look at the switch
statement:
switch (selector expression) { case value1: statement1 [break;] case value2: statement2 [break;] ... case valueN: statementN [break;] [default: statement] }
The switch
statement begins with reserved word switch
and continues with a selector expression that selects one of the subsequent cases or the default case to execute. The selector expression evaluates to an integer, a character, or a string.
Switch and enum constants
The selector expression can also evaluate to an enum
constant. I'll introduce enum
s in a future tutorial.
แต่ละกรณีระบุคำสั่งที่จะดำเนินการ กรณีเริ่มต้นด้วยคำสงวนcase
และค่าที่ติดป้ายกำกับกรณี ตามหลัง:
อักขระโคลอน ( ) คือคำสั่งในการดำเนินการ คำสั่งที่สามารถตามด้วยในการถ่ายโอนการดำเนินการกับคำสั่งแรกหลังจากbreak;
switch
ถ้าไม่มีเลเบลเคสตรงกับค่านิพจน์ตัวเลือกเคสดีฟอลต์ที่เป็นทางเลือกซึ่งขึ้นต้นด้วยคำสงวนdefault
จะดำเนินการ
ด้านล่างนี้เป็นswitch
คำสั่งที่ใช้เพื่อพิจารณาว่าค่าจำนวนเต็มเป็นคู่หรือคี่ (โดยใช้ตัวดำเนินการที่เหลือ) จากนั้นจะแสดงข้อความที่เหมาะสมผ่านกรณีที่มีป้ายกำกับตรงกับส่วนที่เหลือ:
int i = 27; switch (i % 2) { case 0: System.out.println("even"); break; case 1: System.out.println("odd"); }