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.

No hay comentarios: