viernes, 28 de marzo de 2008

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

No hay comentarios: