Программирование на языке Java



Управление выполнением программы - часть 7


class ForTick {

public static void main(String args[]) {

for (int n = 10; n > 0; n--)

System.out.println("tick " + n);

} }

Обратите внимание — переменные можно объявлять внутри раздела инициализации оператора for. Переменная, объявленная внутри опера­тора for, действует в пределах этого оператора.

А вот — новая версия примера с временами года, в которой исполь­зуется оператор for.

class Months {

static String months[] = {

"January", "February", “March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

static int monthdays[]   = { 31, 28,  31, 30, 31,  30, 31, 31, 30, 31, 30, 31 };

static String spring = "spring";

static String summer = "summer";

static String autumn = "autumn";

static String winter = "winter";

static String seasons[]  = { winter, winter, spring, spring, spring, summer, summer, summer, autumn, autumn, autumn, winter };

public static void main(String args[]) {

for (int month = 0; month < 12; month++) {

System.out.println(months[month] + " is a "      +

seasons[month] + " month with " + monthdays[month] + " days.");

} } }

При выполнении эта программа выводит следующие строки:

С:\> Java Months

January is a winter month with 31 days.

February is a winter month with 28 days.

March is a spring month with 31 days.

April is a spring month with 30 days.

May is a spring month with 31 days.

June is a summer month with 30 days.

July is a summer month with 31 days.

August is a summer month with 31 days.

September is a autumn month with 30 days.

October is a autumn month with 31 days.

November is a autumn month with 30 days.

December a winter month with 31 days.




Содержание  Назад  Вперед