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,即使其他標記不是數字。這意味著只有在每一行只輸入一個標記時,我們的程序才能正常工作。


for2. 使用循環計算階乘

讓我們編寫一個程序,不讀取任何內容,而是計算一些內容。有什麼難的。例如,數字的階乘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.

我們需要在這裡有兩個嵌套循環:內部循環負責在給定行上顯示正確數量的星號。

並且需要外循環來循環遍歷這些行。