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つまり、各行にトークンが 1 つだけ入力された場合にのみ、プログラムは正しく動作します。


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場合、すべての数値を乗算した積は になります。f000


3.forループを使用して画面に描画する

画面上に三角形を描くプログラムを書いてみましょう。最初の行は10アスタリスクで構成され、2 行目は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.

ここでは 2 つのネストされたループが必要です。内側のループは、指定された行に正しい数のアスタリスクを表示する役割を果たします。

そして、外側のループはラインをループするために必要です。