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.

我们需要在这里有两个嵌套循环:内部循环负责在给定行上显示正确数量的星号。

并且需要外循环来循环遍历这些行。