viernes, 28 de marzo de 2008

ejercicios en blue j 71 y mas ....

  • Exercise 2.71

Create a Student with name "djb" and id "859012". What
happens when getLoginName is called on this student? Why do you think this is?


Ejercicio 2.71 Crear un de Estudiante con el nombre "djb" y el ID "859012". ¿Qué GetLoginName ocurre cuando se llama a este estudiante? ¿Por qué cree que es?


Exercise 2.72 The String class defines a length accessor method with the followingsignature:
/**
* Return the number of characters in this string.
*/
public int length()

Add conditional statements to the constructor of Student to print an error message
if either the length of the fullName parameter is less than four characters or the
length of the studentId parameter is less than three characters. However, the constructor
should still use those parameters to set the name and id fields, even if the
error message is printed. Hint: Use if statements of the following form (that is, having
no else part) to print the error messages.
if(perform a test on one of the parameters) {
Print an error message if the test gave a true result
}
See Appendix C for further details of the different types of if statement, if necessary.



El ejercicio 2,72 la clase String define un método de acceso de longitud con las siguientes La firma: / ** * Devuelve el número de caracteres en esta cadena. * / Pública int longitud () Añadir condicionales al constructor de Estudiantes para imprimir un mensaje de error Si bien la duración de la fullName parámetro es de menos de cuatro caracteres o la Longitud de la studentId parámetro es de menos de tres caracteres. Sin embargo, el constructor Debería seguir utilizando los parámetros para establecer el nombre y la identificación de los campos, incluso si el Mensaje de error se ha impreso. Sugerencia: Utilice si las declaraciones de la siguiente forma (es decir, después de haber Ninguna otra parte) para imprimir los mensajes de error. Si (es decir, realizar una prueba sobre uno de los parámetros) ( Imprimir un mensaje de error si la prueba dio un resultado verdadero ) Véase el Apéndice C para obtener más detalles de los diferentes tipos de declaración si, de ser necesario.
Exercise 2.73
Challenge exercise Modify the getLoginName method of Student
so that it always generates a login name, even if either of the name and id fields is not
strictly long enough. For strings shorter than the required length, use the whole string.

Ejercicio 2,73 Challenge ejercicio getLoginName Modificar el método de Estudiantes De modo que siempre genera un nombre de inicio de sesión, incluso si cualquiera de los campos de nombre y el ID no es Estrictamente el tiempo suficiente. Por cadenas más corta que la longitud requerida, el uso conjunto de la cadena.


Exercise 2.74 Below is the outline for a Book class, which can be found in the bookexercise
project. The outline already defines two fields and a constructor to initialize the
fields. In this exercise and the next few, you will add further features to the class outline.
Add two accessor methods to the class – getAuthor and getTitle – that return
the author and title fields as their respective results. Test your class by creating
some instances and calling the methods.
/**
* A class that maintains information on a book.
* This might form part of a larger application such
* as a library system, for instance.
*
* @author (Insert your name here.)
* @version (Insert today’s date here.)
*/
public class Book
{
// The fields.
private String author;
private String title;
/**
* Set the author and title fields when this object
* is constructed.
*/
public Book(String bookAuthor, String bookTitle)
{
author = bookAuthor;
title = bookTitle;
}
// Add the methods here ...
}


Ejercicio 2,74 continuación se muestra el esquema de un Libro de clase, que se pueden encontrar en el bookexercise Proyecto. El esquema se define ya dos campos y un constructor para inicializar el Campos. En este ejercicio y los próximos, usted añadir otros elementos a la clase esbozo. Añadir dos métodos de acceso a la clase - getAuthor y getTitle - que regresar El autor y el título de sus respectivos campos como los resultados. Pruebe su clase mediante la creación de Algunos casos y llamando a los métodos. / ** * Una clase que mantiene información sobre un libro. * Esto podría formar parte de un concepto más amplio de aplicación tales * Como un sistema de bibliotecas, por ejemplo. * * @ Autor (Inserte su nombre aquí.) * @ Version (Insertar la fecha de hoy aquí.) * / Public class Libro ( / / Los campos. Privado String autor; String título privado; / ** * Establecer el autor y el título campos cuando este objeto * Se construye. * /
Público de libros (bookAuthor String, String bookTitle) ( Autor = bookAuthor; Title = bookTitle; ) / / Añadir los métodos aquí ... )


Exercise 2.75
Add two methods, printAuthor and printTitle, to the outline
Book class. These should print the author and title fields, respectively, to the terminal
window.


Ejercicio 2,75 Añadir dos métodos, printAuthor y printTitle, al esbozo Libreta de clase. Estos deberán imprimir los campos de título y autor, respectivamente, a la terminal Ventana.
Exercise 2.76
Add a further field, pages, to the Book class to store the number of
pages. This should be of type int, and its initial value should be passed to the
single constructor, along with the author and title strings. Include an appropriate
getPages accessor method for this field.

Ejercicio 2,76 Añadir un nuevo campo, páginas de libros a la clase para almacenar el número de Páginas. Esta debe ser de tipo int, y su valor inicial debe ser pasado a la Único constructor, junto con el autor y el título cadenas. Incluir una adecuada GetPages método de acceso para este campo.

Exercise 2.77
Add a method, printDetails, to the Book class. This should
print details of the author, title, and pages to the terminal window. It is your choice
how the details are formatted. For instance, all three items could be printed on a
single line, or each could be printed on a separate line. You might also choose to
include some explanatory text to help a user work out which is the author and
which is the title, for example
Title: Robinson Crusoe, Author: Daniel Defoe, Pages: 232

Ejercicio 2,77 Añadir un método, printDetails, a la clase de libros. Esto debería Imprimir datos del autor, título, y las páginas de la ventana de terminal. Es su elección Cómo la información es formateada. Por ejemplo, los tres puntos pueden ser impresos en una Sola línea, o que pueden ser impresos en una línea distinta. También puede optar por Algunos incluyen un texto explicativo que ayuda a cabo el trabajo de un usuario que es el autor y Que es el título, por ejemplo Título: Robinson Crusoe, Autor: Daniel Defoe, Páginas: 232
Exercise 2.78
Add a further field, refNumber, to the Book class. This field can store
a reference number for a library, for example. It should be of type String and initialized
to the zero length string ("") in the constructor as its initial value is not passed in a
parameter to the constructor. Instead, define a mutator for it with the following signature:
public void setRefNumber(String ref)
The body of this method should assign the value of the parameter to the refNumber
field. Add a corresponding getRefNumber accessor to help you check that the
mutator works correctly.

Ejercicio 2,78 Añadir un nuevo campo, refNumber, a la clase de libros. Este campo puede almacenar Un número de referencia para una biblioteca, por ejemplo. Debe ser de tipo String y inicializado A la cadena de longitud cero ( "") en el constructor como su valor inicial no es aprobada en un Parámetro al constructor. En lugar de ello, para definir un mutator con la siguiente firma: SetRefNumber público vacío (String ref) El cuerpo de este método debe asignar el valor del parámetro a la refNumber Campo. Añadir un getRefNumber de acceso correspondientes para ayudarle a comprobar que el Mutator funciona correctamente.
Exercise 2.79
Modify your printDetails method to include printing the reference
number. However, the method should print the reference number only if it has
been set – that is, the refNumber string has a non-zero length. If it has not been set,
then print the string "ZZZ" instead. Hint: Use a conditional statement whose test
calls the length method on the refNumber string.


Ejercicio 2,79 Modificar su printDetails método para incluir la impresión de la referencia Número. Sin embargo, el método debe imprimir el número de referencia sólo si ha Se estableció - es decir, la refNumber cadena tiene una longitud distinta de cero. Si no ha sido establecido, Luego imprimir la cadena "ZZZ". Sugerencia: Utilice una sentencia condicional cuya prueba Llama al método de la cadena refNumber.
Exercise 2.80
Modify your setRefNumber mutator so that it sets the refNumber
field only if the parameter is a string of at least three characters. If it is less than
three, then print an error message and leave the field unchanged.
OFWJ_C02.QXD 2/3/06 2:29 pm Page 50

Ejercicio 2,80 Modificar su setRefNumber mutator para que se fija el refNumber Sobre el terreno sólo si el parámetro es una cadena de al menos tres caracteres. Si es menos de Tres, entonces imprime un mensaje de error y dejar el campo sin cambios. OFWJ_C02.QXD 2/3/06 2:29 pm Page 50




Exercise 2.81
Add a further integer field, borrowed, to the Book class. This
keeps a count of the number of times a book has been borrowed. Add a mutator,
borrow, to the class. This should update the field by 1 each time it is called. Include
an accessor, getBorrowed, that returns the value of this new field as its result.
Modify printDetails so that it includes the value of this field with an explanatory
piece of text.



Ejercicio 2,81 Añadir un nuevo campo entero, tomado en préstamo, a la clase de libros. Este Mantiene un conteo del número de veces que un libro se ha tomado en préstamo. Añadir un mutator, Pedir prestado, a la clase. Esto debería actualizar el campo en 1 cada vez que es llamada. Incluir Uno de acceso, getBorrowed, que devuelve el valor de este nuevo campo, como su resultado. Modificar printDetails de modo que incluya el valor de este campo con una exposición Pedazo de texto.

Exercise 2.82
Challenge exercise Create a new project, heater-exercise, within
BlueJ. Edit the details in the project description – the text note you see in the diagram.
Create a class, Heater, that contains a single integer field, temperature.
Define a constructor that takes no parameters. The temperature field should be set
to the value 15 in the constructor. Define the mutators warmer and cooler, whose
effect is to increase or decrease the value of temperature by 5° respectively. Define
an accessor method to return the value of temperature.

Ejercicio 2,82 Challenge ejercicio Crear un nuevo proyecto, calentador de ejercicio, en el marco de BlueJ. Editar los detalles en la descripción del proyecto - el texto nota que se ve en el diagrama. Crear una clase, calentador, que contiene un único campo entero, la temperatura. Definir un constructor que no tiene parámetros. La temperatura sobre el terreno deben establecerse Con el valor 15 en el constructor. Definir el mutators más cálidas y más frías, cuya Efecto es aumentar o disminuir el valor de la temperatura de 5 °, respectivamente. Definir Un método de acceso para devolver el valor de la temperatura.
Exercise 2.83
Challenge exercise Modify your Heater class to define three new
integer fields: min, max, and increment. The values of min and max should be set
by parameters passed to the constructor. The value of increment should be set to
5 in the constructor. Modify the definitions of warmer and cooler so that they use
the value of increment rather than an explicit value of 5. Before proceeding further
with this exercise, check that everything works as before. Now modify the warmer
method so that it will not allow the temperature to be set to a value greater than max.
Similarly modify cooler so that it will not allow temperature to be set to a value
less than min. Check that the class works properly. Now add a method, set-
Increment, that takes a single integer parameter and uses it to set the value of
increment. Once again, test that the class works as you would expect it to by creating
some Heater objects within BlueJ. Do things still work as expected if a negative
value is passed to the setIncrement method? Add a check to this method to prevent
a negative value from being assigned to increment.

Ejercicio 2,83 Challenge ejercicio Modificar su calentador de clase para definir tres nuevos Campos: min, max, y el incremento. Los valores de min y max se fije Por parámetros pasados al constructor. El incremento de valor debe establecerse en 5 en el constructor. Modificar las definiciones de las más cálidas y más frías para que se utilice El incremento de valor más que de una explícita valor de 5. Antes de seguir adelante Con este ejercicio, comprobar que todo funciona como antes. Ahora, modifica el más cálido Método a fin de que no permitirá que la temperatura a ser fijado a un valor mayor que max. Del mismo modo modificar enfriador de manera que no permitirá que la temperatura a ser fijado a un valor Menos de min. Compruebe que la clase funcione correctamente. Ahora añade un método, sistema - Incremento, que toma un parámetro único y lo utiliza para establecer el valor de Incremento. Una vez más, prueba de que la clase funciona como era de esperar a la creación de Calentador algunos objetos dentro de BlueJ. Hacer las cosas todavía funciona como se espera si un negativo Valor se pasa al método setIncrement? Añadir un cheque a este método para evitar Un valor negativo de ser asignado a incremento.

No hay comentarios: