Глава 2
Задача 2.3 Прейскурант лавки древностей.
Модифицируйте программу CurioStore (пример 2.3) так, чтобы она во первых сохраняла данные о количестве каждой древности, а во вторых, выводила сведения о каждой древности в таком порядке:
Решение
Для того, чтобы программа сохраняла данные о количестве предметов, введем в класс Curio еще одну переменную num, в которой будет сохраняться количество. И будем передавать значение этой переменной через четвертый параметр конструктора. Тогда в функции вывода можно будет вывести значение этой переменной вместе с другими переменными.
Код программы:
class CurioStore1
{
/* Curio Store No. 1 by J M Bishop April 2000
* -----------------
* Illustrates the basic form of an object oriented program
*/
// Declare three object variables
Curio mugs, tshirts, carvings;
// The constructor for the program is
// where the initial work gets done
CurioStore1 ()
{
// Create three objects with different initial values
mugs = new Curio("Traditional mugs", 6, "beaded in Ndebele style", 20);
tshirts = new Curio("T-shirts", 30, "sizes M to XL", 50);
carvings = new Curio("Masks", 80, "carved in wood", 8);
// Print out a header
System.out.println("The Polelo Curio Store sells\n");
// Print the values contained in each of the objects
mugs.write();
tshirts.write();
carvings.write();
}
// All programs must have a main method
public static void main (String [ ] args)
{
// Start the program running from its constructor
new CurioStore1 ();
}
}
class Curio
{
// Declare variables related to a curio
String name;
int price;
String description;
int num;
// The constructor copies the initial values
// into the object's variables
Curio (String n, int p, String d, int m)
{
name = n;
price = p;
description = d;
num = m;
}
// a method to output the values of the object's variables
void write ()
{
System.out.println(num +" "+ name + " " + description + " for G" + price);
}
}
В результате выполнения программы мы получим следующие данные:
20 Traditional mugs beaded in Ndebele style for G6
50 T-shirts sizes M to XL for G30
8 Masks carved in wood for G80
Назад |
Начало урока |
Вверх |
Вперед
Содержание