Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practice Task / задачи

.docx
Скачиваний:
26
Добавлен:
14.10.2016
Размер:
26.67 Кб
Скачать
  1. Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables a part number (type String), a part description (type String), a quantity of the item being purchased (type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. Provide a set and a get method for each instance variable. In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a test application named InvoiceTest that demonstrates class Invoice's capabilities.

  1. Create a class called Employee that includes three pieces of information as instance variables a first name (type String), a last name (type String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates class Employee's capabilities. Create two Employee objects and display each object's yearly salary. Then give each Employee a 10% raise and display each Employee's yearly salary again.

Создайте класс, который называется Employee. Данный класс включает в себя три части информации в качестве переменной сущности: first name (тип String), last name (тип String) и monthly salary (тип double). Ваш класс должен иметь конструктор, который инициализирует все три переменные сущности. Обеспечить set и get методы для каждой переменной сущности. Если заработная плата (monthly salary) не является положительной, назначить ей 0.0. Написать main() метод, который демонстрирует возможности класса (создание объектов и вызов методов). Создайте два объекта Employee и отобразите годовую заработную плату каждого объекта. Затем дайте каждому сотруднику 10% надбавки, и отобразите годовую заработную плату каждого сотрудника снова.

  1. Create a class called Date that includes three pieces of information as instance variables a month (type int), a day (type int) and a year (type int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displayDate that displays the month, day and year separated by forward slashes (/). Write a test application named DateTest that demonstrates class Date's capabilities.

Создайте класс Date, который включает в себя три части информации в качестве переменной сущности month (типа int), day (тип int) и year (типа int). Ваш класс должен иметь конструктор, который инициализирует три переменные сущности и предполагается, что допустимые значения являются правильными. Обеспечить set и get методы для каждой переменной сущности. Написать метод displayDate, который отображает месяц, день и год, разделенные косой чертой (/).Написать main() метод, который демонстрирует возможности класса Date.

  1. Modify the given code to produce the output shown in each part of the problem. Use proper indentation techniques. Make no changes other than inserting braces and changing the indentation of the code. The compiler ignores indentation in a Java program. We have eliminated the indentation from the given code to make the problem more challenging. [Note : It is possible that no modification is necessary for some of the parts.]

Измените данный код, чтобы произвести результат, показанный в каждом пункте. Нельзя изменять код, кроме как вставлять фигурные скобки (определять область действия – scope).

if ( y == 8 )

if ( x == 5 )

System.out.println( "@@@@@" );

else

System.out.println( "#####" );

System.out.println( "$$$$$" );

System.out.println( "&&&&&" );

  1. Assuming that x = 5 and y = 8, the following output is produced:

Предположим, что х = 5 и у = 8, следующий вывод будет производится:

@@@@@

$$$$$

&&&&&

  1. Assuming that x = 5 and y = 8, the following output is produced:

Предположим, что х = 5 и у = 8, следующий вывод будет производится:

@@@@@

  1. Assuming that x = 5 and y = 8, the following output is produced:

Предположим, что х = 5 и у = 8, следующий вывод будет производится:

@@@@@

&&&&&

  1. Assuming that x = 5 and y = 7, the following output is produced. [Note : The last three output statements after the else are all part of a block.]

Предположим, что х = 5 и у = 7, следующий вывод будет производится. Примечание: Последние три выходные значения после else выражения являются частью блока.]

#####

$$$$$

&&&&&

  1. Write an application that prompts the user to enter the size of the side of a square, then displays a hollow square of that size made of asterisks. Your program should work for squares of all side lengths between 1 and 20.

Напишите приложение, которое предлагает пользователю ввести размер стороны квадрата, а затем отображает полый квадрат этого размера из звездочек. Ваша программа должна работать для всех квадратов с длинами сторон от 1 до 20.

  1. A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write an application that reads in a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value.

Палиндром представляет собой последовательность символов, которая читается в обе стороны одинаково. Например, каждый пример из следующих пяти цифр целых чисел является палиндром: 12321, 55555, 45554 и 11611. Напишите приложение, которое считывает пятизначное целое число и определяет, является ли она палиндромом. Если число не имеет длину пять цифр, отобразить сообщение об ошибке и позвольте пользователю ввести новое значение.

  1. Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( '*' ); which causes the asterisks to print side by side. A statement of the form System.out.println(); can be used to move to the next line. A statement of the form System.out.print( ' ' ); can be used to display a space for the last two patterns. There should be no other output statements in the program. [Hint: The last two patterns require that each line begin with an appropriate number of blank spaces.]

Напишите приложение, которое отображает следующие шаблоны отдельно, один под другим. Используйте циклы для генерации шаблонов. Все звездочки (*) должны быть напечатаны одним выражением вида System.out.print (“*”); которое распечатывает символы один за другим. Выражение вида System.out.println (); могжет быть использовано для перехода к следующей строке. Выражение вида System.out.print (“ ”); может быть использовано для отображения пробела. В программе не должно быть никаких других выражений вывода. [Подсказка: Последние две модели требуют, чтобы каждая строка начиналась с соответствующего числа пробелов.]

a.

*

**

***

****

*****

******

*******

********

*********

**********

b.

**********

*********

********

*******

******

*****

****

***

**

*

c.

**********

*********

********

*******

******

*****

****

***

**

*

d.

*

**

***

****

*****

******

*******

********

*********

**********

Соседние файлы в папке Practice Task