1. การใช้forลูปเพื่อนับจำนวนบรรทัดที่ป้อน

ลองเขียนโปรแกรมอ่าน10บรรทัดจากแป้นพิมพ์และแสดงจำนวนบรรทัดที่เป็นตัวเลข ตัวอย่าง:

รหัส คำอธิบาย
Scanner console = new Scanner(System.in);
int count = 0;
for (int i = 0; i < 10; i++)
{
   if (console.hasNextInt())
      count++;
   console.nextLine();
}
System.out.println(count);
Create a Scanner object to read data from the console.
Store the number of numbers in the count variable.
Loop from 0 to 10 (not including 10).

If a number is entered,
then increase count by one.
Read a line from the console and don't save it anywhere.

Display the calculated count on the screen.
บันทึก

หากบรรทัดประกอบด้วยโทเค็นหลายรายการที่คั่นด้วยช่องว่าง และตัวแรกเป็นตัวเลข วิธีการhasNextInt()จะส่งกลับtrueแม้ว่าโทเค็นอื่นๆ จะไม่ใช่ตัวเลขก็ตาม นั่นหมายความว่าโปรแกรมของเราจะทำงานได้อย่างถูกต้องต่อเมื่อป้อนเพียงหนึ่งโทเค็นในแต่ละบรรทัด


2. การคำนวณแฟกทอเรียลโดยใช้forลูป

ลองเขียนโปรแกรมที่ไม่อ่านอะไรเลย แต่คำนวณบางอย่างแทน สิ่งที่ยาก 10ตัวอย่างเช่น แฟ กทอเรียลของจำนวน

แฟกทอเรียลของจำนวนn(แสดงด้วยn!) เป็นผลคูณของชุดตัวเลข: 1*2*3*4*5*..*n;

รหัส คำอธิบาย
int f = 1;
for (int i = 1; i <= 10; i++)
   f = f * i;
System.out.println(f);
We store the product of numbers in the f variable.
Loop from 1 to 10 (inclusive).
Multiply f by the next number (save the result in f).
Display the calculated amount on the screen.

ค่าเริ่มต้นคือf = 1เนื่องจากเรากำลังคูณfด้วยตัวเลข ถ้าfเดิมเป็น0ผลคูณของตัวเลขทั้งหมด0จะ0เป็น


3. การใช้forลูปเพื่อวาดบนหน้าจอ

มาเขียนโปรแกรมวาดรูปสามเหลี่ยมบนหน้าจอกันเถอะ บรรทัดแรกประกอบด้วย10เครื่องหมายดอกจัน บรรทัดที่สอง — 9เครื่องหมายดอกจัน จากนั้น8ฯลฯ

รหัส คำอธิบาย
for (int i = 0; i < 10; i++)
{
   int starCount = 10 - i;
   for (int j = 0; j < starCount; j++)
      System.out.print("*");
   System.out.println();
}
Loop through the lines (there should be 10 lines in total).

Calculate how many asterisks should be in the line.
Loop over the individual asterisks
(display starCount asterisks).
Move the cursor to the next line so the lines are separate.

เราจำเป็นต้องมีลูปที่ซ้อนกันสองลูปที่นี่: ลูปในมีหน้าที่แสดงจำนวนเครื่องหมายดอกจันที่ถูกต้องในบรรทัดที่กำหนด

และต้องใช้วงรอบนอกเพื่อวนรอบเส้น