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

Глава 3

Задача 3.19 "Манускрипт "

Измените программу из примера 2.10 ("Книга") так, чтобы класс записывал количество страниц манускрипта, и добавьте метод для вычисления окончательного количества страниц, принимая во внимание редукцию на 80%. Проверьте класс с помощью программы-теста, которая создает 15 глав со сгенерированным случайным образом количеством страниц от 20 до 50.

Решение 2

Создадим класс Book, в котором объявим массив глав Chapter ch[]:

Chapter ch[] = new Chapter[15];

Это естественно, потому, что книга состоит из глав. Класс Chapter сделаем вложенным в класс Book.

В конструкторе будем передавать в параметр массив глав, и переменную, в которой содержится количество элементов массива глав.
Book(String nameCh[], int n){

for (int i = 0;i < n;i++){

ch[i] = new Chapter((i+1), nameCh[i], random_01(20,50));
}
}

Сам массив глав при этом будет находиться в главной программе. Он бы мог находиться в отдельном текстовом файле.

В классе Book сделаем свой метод write(), который в цикле будет перебирать весь инициированный массив глав и сообщеть номер главы, ее имя, количество рукописных страниц. В параметр передаем чило элементов массива глав, который нужно просмотреть:

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

for (int i = 0;i < n;i++){
System.out.println(" Chapter " + ch[i].num + " "+ '"' + ch[i].name + '"' + " " + ch[i].pgs + " pages as manuscripn" );
}
}

Еще согласно условию задачи создадим метод calc(), который будет перебирать инициированный массив глав, и подсчитывать общее количество рукописных страниц во всех главах книги, и затем вычислит учитывая коэффициент редукции количество печатных страниц книги.

void calc(int n){

long Sum = 0;
for (int i = 0;i < n;i++){
Sum = Sum + ch[i].pgs;
}
System.out.println(" " + Sum + " pages as manuscripn" );
System.out.println(" " + Math.round(Sum*0.8) + " pages as typed" );
}

Функция random_01() - вспомогательная. Дает нам случайное число страниц в главах.

int random_01 (int min, int max ){

int z =0;
while(z z = (int) (Math.random()* max);
}
return z;
}

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


class Books {

// Declare massive
String nameChapters[] = {

"Introduction",
"Simple Program",
"Types and Methods",
"Input and Output",
"Manage to stream",
"Massives and Tables",
"Formatting",
"Objects:employing to practic",
"Abstracting and Heritance",
"Graphics and user Interfaces",
"Manage of events",
"Applets in action",
"Work with several routing",
"Work in Net",
"Datastructures and algorithms"
};

int m = 15;// number of chapter

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

Books () {

Book buk = new Book(nameChapters, m);
buk.write(m);
buk.calc(m);
}


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

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


///////////////////////////////

//////////////////////////////////

class Book{

Chapter ch[] = new Chapter[15];
Book(String nameCh[], int n){

for (int i = 0;i < n;i++){

ch[i] = new Chapter((i+1), nameCh[i], random_01(20,50));
}
}

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

for (int i = 0;i < n;i++){
System.out.println(" Chapter " + ch[i].num + " "+ '"' + ch[i].name + '"' + " " + ch[i].pgs + " pages as manuscripn" );
}
}

void calc(int n){
long Sum = 0;
for (int i = 0;i < n;i++){
Sum = Sum + ch[i].pgs;
}
System.out.println(" " + Sum + " pages as manuscripn" );
System.out.println(" " + Math.round(Sum*0.8) + " pages as typed" );
}
class Chapter {

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

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

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

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

System.out.println(" Chapter " + num + " "+ '"' + name + '"' + " " + pgs + " pages as manuscripn" );
}

long colPages(){

long n = Math.round(pgs*0.8);
return n;
}
}

int random_01 (int min, int max ){

int z =0;
while(z z = (int) (Math.random()* max);
}
return z;
}

}


Результат :

Chapter 1 "Introduction" 40 pages as manuscripn
Chapter 2 "Simple Program" 32 pages as manuscripn
Chapter 3 "Types and Methods" 24 pages as manuscripn
Chapter 4 "Input and Output" 44 pages as manuscripn
Chapter 5 "Manage to stream" 23 pages as manuscripn
Chapter 6 "Massives and Tables" 42 pages as manuscripn
Chapter 7 "Formatting" 22 pages as manuscripn
Chapter 8 "Objects:employing to practic" 22 pages as manuscripn
Chapter 9 "Abstracting and Heritance" 43 pages as manuscripn
Chapter 10 "Graphics and user Interfaces" 44 pages as manuscripn
Chapter 11 "Manage of events" 46 pages as manuscripn
Chapter 12 "Applets in action" 43 pages as manuscripn
Chapter 13 "Work with several routing" 44 pages as manuscripn
Chapter 14 "Work in Net" 46 pages as manuscripn
Chapter 15 "Datastructures and algorithms" 32 pages as manuscripn
547 pages as manuscripn
438 pages as typed


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

Hosted by uCoz