domingo, 25 de mayo de 2008

greerwet

dfsgsdfgds

viernes, 4 de abril de 2008

lunes, 31 de marzo de 2008

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.

ejercicios en blue j (2.51 al 2.70)

  • Exercise 2.51

Write an if statement that will compare the value in price against the value in budget. If price is greater than budget then print the message ‘Too expensive’, otherwise print the message ‘Just right’.


Ejercicio 2,51 Escriba una declaración de que si se compara el valor del precio en contra El valor del presupuesto. Si el precio es mayor que el presupuesto luego imprimir el mensaje "Demasiado Caro ", de lo contrario imprimir el mensaje" Sólo derecho ".


If (precio>presupuesto)
{
System.out.prinln(“Demasiado Caro”)
}
Else
{
System.out.println(“Justo”)
}

  • Exercise 2.52

Modify your answer to the previous exercise so that the message ifthe price is too high includes the value of your budget.

Ejercicio 2,52 Modificar su respuesta a la anterior ejercicio a fin de que el mensaje si El precio es demasiado alto incluye el valor de su presupuesto.


If (precio>presupuesto)
{
System.out.println(“Demasiado Caro ya que mi presupuesto es de : ”+presupuesto)
}
Else
{
System.out.println(“Justo”)
}


  • Exercise 2.53

Why does the following version of refundBalance not give the same results as the original?

public int refundBalance()
{
balance = 0;
return balance;
}


What tests can you run to demonstrate that it does not?

Ejercicio 2,53 ¿Por qué la siguiente versión de refundBalance no dar los Mismos resultados que el original?

Pues porque primero balance lo iguala a cero por lo tanto muestra el valor de cero.

¿Qué pruebas puede correr para demostrar que no?

Al igualar a cero.

  • Exercise 2.54

What happens if you try to compile the TicketMachine class with the following version of refundBalance? What do you know about return statements that helps to explain why this version does not compile?


Ejercicio 2,54 ¿Qué ocurre si se intenta compilar la clase TicketMachine con La siguiente versión de refundBalance? ¿Qué sabe usted acerca de regreso declaraciones que ayuda a explicar por qué esta versión No compila?


public int refundBalance()
{
return balance;
balance = 0;
}

Que return solo devuelve el valor de la variable (de acceso), y no permite hacer operaciones o cambiar valores.

  • Exercise 2.55

Add a new method, emptyMachine, that is designed to simulate emptying the machine of money. It should both return the value in total and reset total to be zero.

Ejercicio 2,55 Añadir un nuevo método, emptyMachine, que se usa para simular Vaciar la máquina de dinero. Hay tanto en el valor de retorno y restablecimiento total Total a ser cero.
public emptyMachine


Total=0

  • Exercise 2.56

Is emptyMachine an accessor, a mutator, or both?

Ejercicio 2,56 ¿emptyMachine unde acceso, un mutator, o ambos?


  • Exercise 2.57

Rewrite the printTicket method so that it declares a local variable, amountLeftToPay. This should then be initialized to contain the difference between price and balance. Rewrite the test in the conditional statement to check the value of amountLeftToPay. If its value is less than or equal to zero, a ticket should be printed, otherwise an error message should be printed stating the amount still required. Test your version to ensure that it behaves in exactly the same way as the original version.


Ejercicio 2,57 reescribe el metodo printTicket para que se declara una Variable local, amountLeftToPay. Esto debe ser inicializado para contener la diferencia Entre price y balance. Reescribe la prueba en la sentencia condicional, para comprobar El valor de amountLeftToPay. Si su valor es menor o igual a cero, un ticket Debe ser impreso, de lo contrario un mensaje de error debería ser impreso indicando la cantidad Sigue siendo necesaria. Su versión de prueba para asegurarse de que se comporta exactamente de la misma manera que En la versión original.


public void printTicket2()
{
amountLeftToPay=balance-price
if(amountLeftToPay <= 0)
{
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();

// Update the total collected with the price.
total = total + price;
// Reduce the balance by the prince.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");

}
}

  • Exercise 2.58

Challenge exercise Suppose we wished a single TicketMachine object to be able to issue tickets with different prices. For instance, users might press a button on the physical machine to select a particular ticket price. What further methods and/or fields would need to be added to TicketMachine to allow this kind of functionality? Do you think that many of the existing methods would need to be
changed as well?
Save the better-ticket-machine project under a new name and implement your changes to the new project.


Ejercicio 2,58 Challenge ejercicio Supongamos que desea un único Objeto TicketMachine de poder emitir tickets con precios diferentes. Por ejemplo, los usuarios podrían prensa Un botón en la máquina física para seleccionar un precio de ticket. ¿Qué nuevas Métodos y / o campos habrá que añadir a TicketMachine a permitir este tipo De la funcionalidad? ¿Cree usted que muchos de los métodos existentes sería necesario Cambiado también? Guardar el better-ticket-machine proyecto con un nuevo nombre y aplicar su Cambios en el nuevo proyecto.


  • Exercise 2.59

List the name and return type of this method:


public String getCode()
{
return code;
}


Ejercicios de 2,59 Lista el nombre y tipo de retorno de este método:


public String getCode()
{

return code;
}

es un metodo de acceso llamado getCode

  • Exercise 2.60

List the name of this method and the name and type of its parameter:

public void setCredits(int creditValue)
{
credits = creditValue;
}


Ejercicios 2,60 Lista el nombre de este método y el nombre y el tipo de su parámetro:


public void setCredits(int creditValue)
{
credits = creditValue;
}

Es un metodo es tipo Void (es decir mutante, ya que se pueden hacer cambios) el cual tiene el nombre de setCredits, y su parámetro se llama creditValue y es de tipo entero, ademas es un parámetro de asiganacion.

  • Exercise 2.61

Write out the outer wrapping of a class called Person. Remember to include the curly brackets that mark the start and end of the class body, but otherwise
leave the body empty.


Ejercicio 2,61 Escriba la firma de una clase llamada Pearson. Recuerde Para incluir las llaves que marcan el inicio y final de la clase el cuerpo, pero de otro modo Dejar el cuerpo vacío.

Private void pearson()
{

}





  • Exercise 2.62

Write out definitions for the following fields:
_ A field called name of type String.
_ A field of type int called age.
_ A field of type String called code.
_ A field called credits of type int.

Ejercicio 2,62 Escriba definiciones de los siguientes campos:


-Un campo llamado nombre de tipo String.
Solo acepta caracteres de tipo cadena

-Un campo de tipo int llamada edad.
Solo acepta números enteros y no letras

-Un campo de tipo String llamado código.
Solo acepta caracteres tipo cadena

-Un campo de los llamados créditos de tipo int.
Solo acepta números, valores enteros


  • Exercise 2.63

Write out a constructor for a class called Module. The constructor
should take a single parameter of type String called moduleCode. The body of
the constructor should assign the value of its parameter to a field called code. You
don’t have to include the definition for code, just the text of the constructor.


Ejercicio 2,63 Escriba un constructor para una clase llamada Módulo. El constructor Debería tener un único parámetro de tipo String llamado moduleCode. El cuerpo de El constructor debe asignar el valor de su parámetro a un campo llamado código. Usted No tienen que incluir la definición de código, sólo el texto del constructor.

Public module (string moduleCode)
{
Code= moduleCode;
}


  • Exercise 2.64

Write out a constructor for a class called Person. The constructor
should take two parameters. The first is of type String and is called myName. The
second is of type int and is called myAge. The first parameter should be used to
set the value of a field called name, and the second should set a field called age.
You don’t have to include the definitions for fields, just the text of the constructor.

Ejercicio 2,64 Escriba un constructor para una clase llamada Persona. El constructor Debería tener dos parámetros. La primera es de tipo String y se llama myName. El Segundo es de tipo int y se llama myAge. El primer parámetro debe utilizarse para Fijar el valor de un campo llamado nombre, y el segundo debe establecer un campo llamado edad. Usted no tiene que incluir las definiciones de los campos, sólo el texto del constructor.

Public pearson (String myName, int myAge)
{
Name=myName;
Age=myAge;
}

  • Exercise 2.65

Correct the error in this method:
public void getAge()
{
return age;
}
Ejercicio 2,65 Corregir el error de este método: Solucion:

Public int getAge()
{
return age;
}


  • Exercise 2.66

Write an accessor method called getName that returns the value
of a field called name, whose type is String.

Ejercicio 2,66 Escriba un método de acceso llamado getName que devuelve el valor De un campo llamado nombre, cuyo tipo es String.


public String getName()
{
return name;
}


  • Exercise 2.67

Write a mutator method called setAge that takes a single parameter
of type int and sets the value of a field called age.

Ejercicio 2,67 Escriba un método mutante llamado setAge que toma un solo parámetro De tipo int y establece el valor de un campo llamado edad.

Public void setAge (int age)
{

}

  • Exercise 2.68

Write a method called printDetails for a class that has a field of type String called name. The printDetails method should print out a String of the form “The name of this person is” followed by the value of the name field. For instance, if the value of the name field is “Helen” then printDetails would print: The name of this person is Helen

Ejercicio 2,68 Escriba un método llamado printDetails para una clase que tiene un campo De tipo String llamado nombre. El método printDetails debería imprimir una Cadena de texto del tipo "El nombre de esta persona es", seguido por el valor de El campo de nombre. Por ejemplo, si el valor del campo de nombre es "Helen", luego PrintDetails imprimiría: El nombre de esta persona es Helen

….
Private void PrintDetails()
{
System.out.println(“el nombre de esta persona es ”+name)
}

  • Exercise 2.69

Draw a picture of the form shown in Figure 2.3 representing the
initial state of a Student object following its construction with the following actual
parameter values:
new Student("Benjamin Jonson", "738321")

Ejercicio 2,69 dibujar un panorama de la forma en que la figura que representa el 2,3 Estado inicial de un objeto de Estudiantes después de su construcción, con los siguientes efectivos Valores de los parámetros:
Nuevo estudiante ("Benjamin Jonson", "738321")

  • Exercise 2.70

What would be returned by getLoginName for a student with the
name "Henry Moore" and the id "557214"?

Ejercicio 2,70 ¿Cuál ha de ser devuelto por getLoginName para un estudiante con el Nombre de "Henry Moore" y la ID "557214"?

Pues devuelve el

miércoles, 12 de marzo de 2008

ejercicios en blue j (2.29 al 2.50) de tarea....

  • Exercise 2.29
How can we tell from just its header that getPrice is a method and not a constructor?
public void setPrice(int ticketCost)

Ejercicio 2,29 ¿Cómo podemos decir de su cabecera que setPrice es un método Y no un constructor? public void setPrice(int ticketCost)

En la linea de codigo del ejercicio 2.29 podemos visualizar un metodo como es posible saber esto?
Es facil, para crear un constructor, es necesario que devuelva un valor, y ademas se especifique antes del nombre el tipo de dato.
Como nuestra linea de codigo no devuelve ningun valor, debido a que es "void" podemos decir que se trata de un metodo.




  • Exercise 2.30
Complete the body of the setPrice method so that it assigns the
value of its parameter to the price field.

Ejercicio 2,30 completa el cuerpo de l metodo setPrice para que se asigna el Valor de su parámetro para el campo price.


public void setPrice(int ticketCost)
{
Price=ticketCost;
}




  • Exercise 2.31

Complete the body of the following method, whose purpose is to
add the value of its parameter to a field named score.
/**
* Increase score by the given number of points.
*/
public void increase(int points)
{
...
}


Ejercicio 2.31
Completa el cuerpo del siguiente metodo, el cual su proposito es agregar el valor de su parametro al campo llamado score.

/**
* Increase score by the given number of points.
*/
public void increase(int points)
{
score=score+points;
}




  • Exercise 2.32

Can you complete the following method, whose purpose is to subtract the value of its parameter from a field named price?
/**
* Reduce price by the given amount.
*/
public void discount(int amount)
{
...
}


Ejercicio 2.32 Puede completar el siguiente método, cuyo objetivo es restar El valor de su parámetro del campo llamado price? / ** * Reducir el precio por la cantidad determinada. * / public void discount(int amount)
( ... )


Solucion:

/**
* Reduce price by the given amount.
*/
public void discount(int amount)
{
price=price-amount;
}



  • Exercise 2.33

Add a method called prompt to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print something like: Please insert the correct amount of money.

Ejercicio 2,33 Añadir un método llamado prompt a la clase TicketMachine. Este Deben tener un vacío tipo de retorno y no tener parámetros. El cuerpo del método
Debe imprimir algo como: Por favor, introduzca la cantidad correcta de dinero.


public void Prompt()
{
System.out.println("por favor inserte el monto correcto de dinero");
}



  • Exercise 2.34

Add a showPrice method to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print something like: The price of a ticket is xyz cents.
where xyz should be replaced by the value held in the price field when the method is called.

Ejercicio 2.34 Añadir un metodo showPrice a la clase TicketMachine. Este Debe tener un tipo de retorno void y no tener parámetros. El cuerpo del método Debe imprimir algo como: El precio del billete es xyz centavos. Donde xyz debe sustituirse por el valor celebrada en el campo price cuando el método Se llama.
public void showprice()
{
System.out.println("el precio del ticket es:"+price+"centavos");
}



  • Exercise 2.35

Create two ticket machines with differently priced tickets. Do calls
to their showPrice methods show the same output, or different? How do you explain
this effect?



Ejercicio 2,35 Cree dos ticket machines con diferente precio de los tickets. Hacer llamadas a sus metodos ShowPrice, muestra la misma salida, o diferentes? ¿Cómo explica Este efecto?

Salen diferentes cantidades ya que cada objeto se tomad e manera diferente, por lo tanto el precio de los tickets son diferentes, ejemplo:





  • Exercise 2.36

What do you think would be printed if you altered the fourth statement of printTicket so that price also has quotes around it, as follows? System.out.println("# " + "price" + " cents.");

Ejercicio 2,36 ¿Qué cree usted que sería impreso si alterado la cuarta declaración PrintTicket de manera que el precio también tiene comillas en torno a ella, de la siguiente manera? System.out.println ( "#" + "precio" + "centavos".);

Pues imprimiría en la terminal la palabra price en vez del valor de este campo, ejemplo:



  • Exercise 2.37

What about the following version? System.out.println("# price cents.");

Ejercicio 2,37¿Qué hay de la siguiente versión? System.out.println ( "# precio centavos.");

Pues imprimiria en pantalla las palabras que estan dentro de las comillas, ejemplo:
"# precio centavos."


  • Exercise 2.38

Could either of the previous two versions be used to show the price of tickets in different ticket machines? Explain your answer.

Ejercicio 2,38 ¿Podría cualquiera de las dos versiones anteriores se utilizarán para mostrar el Precio de las entradas en diferentes máquinas? Explica tu respuesta.

Pues ninguna de la sdos anteriores nos hervirían para mostrar el prcio de las entradas en la diferentes maquinas ya que las dos nos mostrarían la misma leyenda. En cambio si lo ponemos de la siguiente manera, nos mostraria diferentes valores ya que en el nos referimos al valor del campo price:

System.out.println ( "# “+precio +”centavos.");



Before attempting these exercises, be sure that you have a good understanding of
how ticket machines behave, and how that behavior is implemented through the
fields, constructor, and methods of the class.

Antes de intentar estos ejercicios, asegúrese de que usted tiene un buen conocimiento de Cómo se comportan las máquinas de tickets, y la manera en que la conducta se ejecuta a través de la Campos, constructor, y los métodos de la clase.


  • Exercise 2.39

Modify the constructor of TicketMachine so that it no longer has a parameter. Instead, the price of tickets should be fixed at 1000 cents. What effect does this have when you construct ticket machine objects within BlueJ?


Ejercicio 2,39 Modificar el constructor de TicketMachine a fin de que ya no tiene Un parámetro. En cambio, el precio de los tickets debe fijarse en 1000 centavos. ¿Qué efecto Tiene esto cuando usted construir objetos dentro de la máquina de tickets de BlueJ?


Pues debemos asignar al campo price el valor de 1000 directamernte, ejmplo:

Price=1000

Asi ya no podemos elegir libremente el precio de los tickets.


  • Exercise 2.40

Implement a method, empty, that simulates the effect of removing all money from the machine. This method should have a void return type, and its body should simply set the total field to zero. Does this method need to take any parameters?
Test your method by creating a machine, inserting some money, printing some tickets, checking the total, and then emptying the machine. Is this method a mutator or an accessor?



Ejercicio 2,40 Aplicar un método, vacío, que simula el efecto de eliminar Todo el dinero de la máquina. Este método debería tener un tipo de retorno void, y su cuerpo debería simplemente establecer el campo total a cero. Este método necesario que realice ninguna Parámetros?
Pruebe su método mediante la creación de una máquina, la inserción de un poco de dinero, la impresión Algunos tickets, el control total y, a continuación, vaciar la máquina. ¿Es este método unMutator o uno de acceso?

Cuando en la firma del metodo contiene la palabra reservada VOID dicho metodo no devuelve ningun valor por lo tanto es mutante, como lo es este caso, pero si necesita una sentencia que debe igualar el campo total a cero

Public void eliminar()
{
Total=0
}


  • Exercise 2.41

Implement a method, setPrice, that is able to set the price of tickets to a new value. The new price is passed in as a parameter value to the method. Test your method by creating a machine, showing the price of tickets, changing the price, and then showing the new price. Is this method a mutator?

Ejercicio 2,41 Aplicar un método, setPrice, que es capaz de fijar el precio de los tickets para un nuevo valor. El nuevo precio es pasado como parámetro en el valor al Método. Pruebe su método mediante la creación de una máquina, que muestra el precio de las tickets, Cambiar el precio y, a continuación, muestra el nuevo precio. ¿Es este método un mutador?


  • Exercise 2.42

Give the class two constructors. One should take a single parameter that specifies the price, and the other should take no parameter and set the price to be a default value of your choosing. Test your implementation by creating machines via the two different constructors.

Ejercicio 2,42 Dar la clase dos constructores. Uno debe tener un único parámetro Que se especifique el precio, y el otro debería tener ningún parámetro y establece el precio De ser un valor por defecto de su elección. Pruebe su aplicación mediante la creación de máquinas A través de los dos constructores diferentes.

  • Exercise 2.43

Check that the behavior we have discussed here is accurate by creating a TicketMachine instance and calling insertMoney with various actual parameter values. Check the balance both before and after calling insertMoney. Does the balance ever change in the cases when an error message is printed? Try to
predict what will happen if you enter the value zero as the parameter, and then see if you are right.


Ejercicio 2,43 Compruebe que la conducta que hemos discutido aquí es correcta por La creación de una instancia y TicketMachine llamando insertMoney con diversos real Valores de los parámetros. Consultar el saldo antes y después de llamar insertMoney. ¿El equilibrio nunca cambio en el caso de un mensaje de error cuando se imprime? Intente Predecir lo que sucederá en caso de que introduzca el valor cero como el parámetro, y luego ver si Tiene usted razón.


Cuando insertamos el valor de cero en el parámetro, nos devuelve un mensaje como este:

  • Exercise 2.44

Predict what you think will happen if you change the test in insertMoney to use the greater-than or equal-to operator:
if(amount >= 0)

Check your predictions by running some tests. What difference does it make to the
behavior of the method?

Ejercicio 2,44 Predecir lo que piensa que va a suceder si el cambio en la prueba InsertMoney de utilizar el mayor que o igual-a-operador:
If (amount > = 0)
Chequea tu predicciones ejecutando algunas pruebas. ¿Qué supone para la Comportamiento del método?

Pues al insertar en el parámetro la cantidad cero, lo aceptaria sin marcar ningun mensaje ya que tambien lo contempla (0)al poner mayor o igual que cero.

  • Exercise 2.45

In the shapes project we looked at in Chapter 1 we used a boolean field to control a feature of the circle objects. What was that feature? Was it well suited to being controlled by a type with only two different values?


Ejercicio 2.45 En el proyecto shapes vimos en el capítulo 1 se utilizó un Campo lógico para controlar una característica de los objetos círculo. Lo que se que función? ¿Fue Adecuado para ser controlado por un tipo con sólo dos valores diferentes?

El campo del cual se habla es el siguiente:

private boolean isVisible;

isVisible = false;


yo creo que si es adecuado ya que este solo puede tomar dos valores ya sea falso o verdadero, es decir puede el circulo sea visible o no.

  • Exercise 2.46

In this version of printTicket we also do something slightly different with the total and balance fields. Compare the implementation of the method in Code 2.1 with that in Code 2.8 to see whether you can tell what those differences are. Then check your understanding by experimenting within BlueJ.


Ejercicio 2,46 En esta versión de printTicket también hacer algo ligeramente Diferentes con los campos total y balance. Comparar la aplicación de el Método en el Código con la de 2,1 Código 2,8 a ver si usted puede decir lo que los Diferencias. Luego, compruebe su comprensión por la experimentación dentro de BlueJ.


Pues en la primera hace un incremento del total mas el precio.
total = total + price;
mientras que en la segunda hace un decremento del balance menos el precio.
balance = balance - price;

  • Exercise 2.47

After a ticket has been printed, could the value in the balance field ever be set to a negative value by subtracting price from it? Justify your answer.


Ejercicio 2,47 Después de un ticket ha sido impreso, podría el valor en el Campo balance nunca ser fijado a un valor negativo restando el precio de este? Justifica tu respuesta.


NO, ya que antes se pone la condición if (balance >= price), si cumple hará lo que sigue, que en este caso es restar el precio de balance, y como debido a la condición balance siempre será mayor o igual que cero entonces no podrá dar un resultado negativo.

  • Exercise 2.48

So far we have introduced you to two arithmetic operators, + and –,
that can be used in arithmetic expressions in Java. Take a look at Appendix D to find
out what other operators are available.

Ejercicio 2,48 Hasta el momento hemos introducido usted a dos operadores aritméticos, + y -, Que se pueden utilizar en expresiones aritméticas en Java. Echa un vistazo en el Apéndice D de encontrar Lo que se dispone de otros operadores.

  • Exercise 2.49

Write an assignment statement that will store the result of multiplying
two variables, price and discount, into a third variable, saving.

Ejercicio 2,49 Escribir una cesión declaración de que se guarde el resultado de multiplicar Dos variables, el precio y descuento, en una tercera variable, el ahorro.

ahorro=precio * descuento


  • Exercise 2.50

Write an assignment statement that will divide the value in total
by the value in count and store the result in mean.

Ejercicio 2,50 Escribir una cesión declaración que dividia el valor en total Por el valor de contar y almacenar el resultado en media.

Mean=count / store


miércoles, 27 de febrero de 2008

ejercicios en blue j (2.11 al 2.28)

  • Exercise 2.11

What do you think is the type of each of the following fields?
private int count;
private Student representative;
private Server host;

Ejercicio 2,11 ¿Cuál cree que es el tipo de cada uno de los siguientes campos?

private int count; PRIVADO- ENTERO
private Student representative; PRIVADO - STRING
private Server host; PRIVADO- STRING





  • Exercise 2.12

What are the names of the following fields?
private boolean alive;
private Person tutor;
private Game game;

Ejercicio 2,12
¿Cuáles son los nombres de los siguientes campos?


private boolean alive; PRIVADO- BOOLEANO
private Person tutor; PRIVADO- STRING
private Game game; PRIVADO- STRING




  • Exercise 2.13

In the following field declaration from the TicketMachine class
private int price;
does it matter which order the three words appear in? Edit the TicketMachine class to
try different orderings. After each change, close the editor. Does the appearance of the
class diagram after each change give you a clue as to whether or not other orderings are
possible? Check by pressing the Compile button to see if there is an error message.
Make sure that you reinstate the original version after your experiments!

Ejercicio 2,13 En el siguiente campo declaración de la clase TicketMachine
private int price;

¿Importa el orden que aparecen en tres palabras? Modificar la clase a la TicketMachine Probar diferentes ordenamientos. Después de cada cambio, cierre el editor. ¿La aparición de la Diagrama de clase después de cada cambio de darle una pista en cuanto a si o no son otros ordenamientos Posible?
Checa pulsando el botón Compilar para ver si hay un mensaje de error. Asegúrese de que restablecer la versión original después de sus experimentos!


S i cambiamos el orden de las palabras y lo compilamos nos manda un mensaje de error como el siguiente:





  • Exercise 2.14

Is it always necessary to have a semicolon at the end of a field declaration?
Once again, experiment via the editor. The rule you will learn here is an
important one, so be sure to remember it.

Ejercicio 2,14 ¿Es siempre necesario contar con un punto y coma al final de una declaración sobre el terreno? Una vez más, el experimento a través de editor. La norma podrá aprender aquí es un Importante, así que asegúrese de recordarla.
Si es necesario poner el punto y coma al final de un a declaracion, ya que de lo contrario nos marca un error (ya que es una regla de sintaxis). Ejemplo:

  • Exercise 2.15

Write in full the declaration for a field of type int whose name is
status.

Ejercicio 2,15 Escribir en pleno la declaración de un campo de tipo int cuyo nombre es status.


INT STATUS

  • Exercise 2.16

To what class does the following constructor belong?
public Student(String name)

Ejercicio 2,16 ¿En qué clase hace lo siguiente constructor pertenecen? public Student(String name)

A la clase “ public class Student”

  • Exercise 2.17

How many parameters does the following constructor have and
what are their types?
public Book(String title, double price)


2,17 ejercicio ¿Cuántos parámetros hace lo siguiente constructor y han ¿Cuáles son sus tipos?
public Book(String title, double price)

Este constructor hace 2 parametros, el primero “title” es de tipo cadena y el segundo “price”es de tipo double.

  • Exercise 2.18

Can you guess what types some of the Book class’s fields might
be? Can you assume anything about the names of its fields?

Ejercicio 2.18 ¿Puede adivinar qué tipos podrian ser algunos campos de la clase Book ?
¿Puede asumir nada sobre los nombres de sus campos?

Titulo, autor, editorial, etc.


  • Exercise 2.19

Suppose that the class Pet has a field called name that is of type
String. Write an assignment statement in the body of the following constructor so
that the name field will be initialized with the value of the constructor’s parameter.

public Pet(String petsName)
{
...
}


Ejercicio 2,19 Supongamos que la clase Pet (mascotas) tiene un campo llamado name que es del tipo String. Escribir una sentencia de asignación en el cuerpo de el siguiente constructor Que el campo name se inicia con el valor del parámetro del constructor.

Pues se tiene que hacer lo siguiente:

Public Pet(String petsName)
{name= petsName;}

  • Exercise 2.20

Challenge exercise What is wrong with the following version of the onstructor of TicketMachine?


public TicketMachine(int ticketCost)
{
int price = ticketCost;
balance = 0;
total = 0;
}

Once you have spotted the problem, try out this version in the naive-ticket-machine
project. Does this version compile? Create an object and then inspect its fields. Do
you notice something wrong about the value of the price field in the inspector with
this version? Can you explain why this is?


Ejercicio 2,20 ¿Qué hay de malo en la siguiente versión del Constructor de TicketMachine?

public TicketMachine(int ticketCost)
{
int price = ticketCost;
balance = 0;
total = 0;
}


Esta parte es erronea:


int price = ticketCost;
ya que en ella volvemos a declarar price como tipo entero y lo toma como parámetro diferente al de price.


Una vez que haya visto el problema, pruebe esta versión ingenua en proyecto naive-ticket-machine ¿se compila esta version? Crear un objeto y, a continuación, inspeccionar sus campos. ¿ Usted nota algo mal sobre el valor del precio en el campo con el inspector Esta versión? ¿Puede explicar por qué es?

No compila ya que marca un error de sintaxis.

  • Exercise 2.21

Compare the getBalance method with the getPrice method.
What are the differences between them?

Ejercicio 2,21 Comparar el método getBalance con el método getPrice. ¿Cuáles son las diferencias entre ellos?
Aparte de los nombres; En la estructura no hay diferencias, nada mas que getPrice devuelve el valor del ticket que se declaro cuando se crea el objeto mientras que getBalance sirve para comprobar que la máquina tiene un registro de la cantidad insertada.

  • Exercise 2.22

If a call to getPrice can be characterized as ‘What do tickets
cost?’, how would you characterize a call to getBalance?

Ejercicio 2,22 Si una llamada a getPrice puede caracterizarse como "¿Cuál es el costo de un ticket? ", ¿Cómo se puede caracterizar a una llamada getBalance?

Pues getBalance es el que hace el registro de las cantidades que se inserta y cambia cada vez que insertamos una cantidad.


  • Exercise 2.23

If the name of getBalance is changed to getAmount, does the
return statement in the body of the method need to be changed, too? Try it out within
BlueJ.

Ejercicio 2,23 Si el nombre de getBalance se cambia a getAmount, ¿el Volver declaración en el cuerpo del método que hay que cambiar, también?

Pues al cambiar el nombre de getBaalance a getAmount no tengo que cambiar nada en el cuerpo del metodo ya que son independientes.

  • Exercise 2.24

Define an accessor method, getTotal, that returns the value of
the total field.

Ejercicio 2,24 Definir un método de acceso, getTotal, que devuelve el valor de El total del campo.

public int getTotal()
{
return Total;
}

  • Exercise 2.25

Try removing the return statement from the body of getPrice.
What error message do you see now when you try compiling the class?
2,25 Ejercicio Prueba a eliminando la declaracion de retorno del cuerpo de getPrice. ¿Qué mensaje de error es el que usted ve ahora al tratar de compilar la clase?


  • Exercise 2.26

Compare the method signatures of getPrice and printTicket in Code 2.1. Apart from their names, what is the main difference between them?
Ejercicio 2,26 Comparar el método de las firmas getPrice y printTicket En el Código de 2,1. Aparte de sus nombres, ¿cuál es la principal diferencia entre ellos?

La principal diferencia entre estos es que uno es de tipo entero mientras que el otro es un metodo mutante es decir que tiene void

public int getPrice()
{

return price;
}

/**


public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();

// Update the total collected with the price.
total = total + price;
// Reduce the balance by the prince.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");

}
}

  • Exercise 2.27

Do the insertMoney and printTicket methods have return
statements? Why do you think this might be? Do you notice anything about their
headers that might suggest why they do not require return statements?


Ejercicio 2,27 ¿la insertMoney y printTicket métodos tienen declaraciones de retorno ? ¿Por qué cree que podría ser? ¿Nada acerca de su anuncio Cabeceras que puede sugerir la idea de la razón por la que no requieren declaraciones de retorno?


public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount: " +
amount);
}
}

public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();

total = total + price;
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");

}
}

Pues yo creo que como en estos dos metodos se hacen operaciones (cambios) es necesario ponerle el VOID, ya que con otro tipo no se puede.

  • Exercise 2.28
Create a ticket machine with a ticket price of your choosing. Before
doing anything else, call the getBalance method on it. Now call the insertMoney
method (Code 2.6) and give a non-zero positive amount of money as the actual
parameter. Now call getBalance again. The two calls to getBalance should show
different output because the call to insertMoney had the effect of changing the
machine’s state via its balance field.


Ejercicio 2,28 Crear un ticket máquina con un ticket de precio de su elección. Antes de hacer algo más, llame al metodo getBalance en ella. Tiene la palabra el metodo insertMoney Método (Código 2.6) y dar un no-cero positivos cantidad de dinero como el actual Parámetro. Ahora llama getbalance.
Las dos llamadas a getBalance debe mostrar Diferentes de salida debido a la llamada a insertMoney tuvo el efecto de cambiar la Máquina del Estado a través de su equilibrio sobre el terreno.