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모든 숫자를 곱한 값은 입니다 .f000


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.

여기에는 두 개의 중첩 루프가 필요합니다. 내부 루프는 주어진 줄에 올바른 수의 별표를 표시하는 역할을 합니다.

그리고 라인을 반복하려면 외부 루프가 필요합니다.