Назад | Начало урока | Вперед
Содержание

Глава 2

Задача 2.10 Книга

Мы разработаем программу, которая будет сохранять инф об учебнике. Начнем с определения класса Chapter (глава), который содержит переменные для названия главы и количества страниц в ней. Используя данные о настоящей книге в качестве тестовых, инициализируем объекты для первых четырех глав. Впоследствии мы будем работать с этими объектами, вычисляя общее количество страниц в книге и среднее количество страниц в главе. Страница, написанная вручную содержит примерно 80% инф печатной страницы. С помощью наших 4-х объектов вычислим количество рукописных страниц для каждой главы. Например, если первая глава содержит 20 страниц, то рукописная будет содержать 20/0,8 = 25 страниц, поэтому вторая глава начинается со страницы 26, а не 21.

Решение

Определим класс Chapter. Он имеет три переменные - название главы, число страниц и номер главы. Инициализируем в конструкторе эти переменные. Так же определим метод, который выводит на экран значения переменных.

class Chapter {

// Declare variables related to a curio
String name; // имя главы
long str; // число страниц
int num; // номер главы

// The constructor
Chapter (String n, int s, int j) {

name = n;
str = s;
num = j;
}

// a method to output the values of the object's variables void write () {

System.out.println(" Chapter " + num + " "+ '"' + name + '"' + " " + str + " pages" );
}
}

В главной программе определим четыре объекта для печатных страниц и четыре объекта для рукописных страниц, и проведем все необходимые нам операции с этими объектами.

Число рукописных страниц, соответствующее числу печатных будет больше на величину, которую определяет следующее выражение:

gl_1.str = Math.round(ch1.str/0.8);

Код программы:


class Book {

// Declare object variables
Chapter ch1, ch2, ch3, ch4; // главы печатные
Chapter gl_1, gl_2, gl_3, gl_4; // главы рукописные

// The constructor for the program is
// where the initial work gets done

Book () {

// Create three objects with different initial values
ch1 = new Chapter("Introduction", 13, 1);
ch2 = new Chapter("Simple Program", 33, 2);
ch3 = new Chapter("Types and Methods", 49, 3);
ch4 = new Chapter("Input and Output", 40, 4);

// Print out a header

System.out.println();
System.out.println(" Typed chapters: ");
System.out.println();

// Print the values contained in each of the objects
ch1.write();
ch2.write();
ch3.write();
ch4.write();

// calculate new strings

gl_1 = new Chapter("Introduction", 0, 1);
gl_2 = new Chapter("Simple Program", 0, 2);
gl_3 = new Chapter("Types and Methods", 0, 3);
gl_4 = new Chapter("Input and Output", 0, 4);

gl_1.str = Math.round(ch1.str/0.8);
gl_2.str = Math.round(ch2.str/0.8);
gl_3.str = Math.round(ch3.str/0.8);
gl_4.str = Math.round(ch4.str/0.8);

System.out.println();
System.out.println(" Handling script chapters: ");
System.out.println();

// Print the values contained in each of the objects
gl_1.write();
gl_2.write();
gl_3.write();
gl_4.write();

}


// All programs must have a main method public static void main (String [ ] args) {

// Start the program running from its constructor
new Book ();
}
}


class Chapter {

// Declare variables related to a curio
String name;
long str;
int num;

// The constructor
Chapter (String n, int s, int j) {

name = n;
str = s;
num = j;
}

// a method to output the values of the object's variables
void write () {

System.out.println(" Chapter " + num + " "+ '"' + name + '"' + " " + str + " pages" );
}
}


Результат :


Typed chapters:

Chapter 1 "Introduction" 13 pages
Chapter 2 "Simple Program" 33 pages
Chapter 3 "Types and Methods" 49 pages
Chapter 4 "Input and Output" 40 pages

Handling script chapters:

Chapter 1 "Introduction" 16 pages
Chapter 2 "Simple Program" 41 pages
Chapter 3 "Types and Methods" 61 pages
Chapter 4 "Input and Output" 50 pages


Назад | Начало урока | Вверх | Вперед
Содержание

Hosted by uCoz