Total de visualizações de página

domingo, 10 de maio de 2015


À minha querida mãe Amélia:

Feliz Dia das Mães! Happy Mother's Day! 

À minha querida mãe Amélia:

Sei que Deus tinha outros planos para a Senhora, levando-a bem cedo para junto dEle. Muitas vezes procuro lembrar de sua face e dos momentos de minha infância, porém pouco consigo recordar. Porém eu sei através de meus irmãos que a Senhora era um anjo em nossas vidas.

Não se preocupe Mãe, a senhora me deixou em boas mãos. A Mariinha cuidou bem de mim, e ajudou na formação de meu caráter. A pessoa que acolheu todos os seus 7 filhos, como se fossem dela.

Da minha Tia Darci, que mesmo à distância, nunca nos abandonou, e cuidava de mim como um filho.

Porém Mãe, a gente cresce e bate asas, e vai morar longe. E quando menos se espera, aparece outra mãe para nos adotar. Com seu jeito carinhoso e doce veio a Conceição, que sempre encontra espaço em seu coração para mais um filho.

Até parece que ai do céu, a Senhora fica escolhendo nos dedos, a mãe substituta para nos proteger.

Obrigado!

sábado, 11 de dezembro de 2010

Implement a class Time that keeps track of time by keeping the hour, minutes and seconds Note: The object will keep the time in military format, in a 24 hour clock.

CS 120 Assignment #7

Project Specifications

1.      Implement a class Time that keeps track of time by keeping the hour, minutes and seconds Note: The object will keep the time in military format, in a 24 hour clock. 
2.      Remember to validate all values!
3.      Provide the following methods:
·        At least 2 constructors.
·        Provide accessor and mutators for all instance variables.
·        The toString() method will provide the time in military format.
·        Implement a method to provide the time in standard format using AM/PM.
·        Format the display to show two digits for minutes and seconds.
·        Provide a method timeOfDay() that returns the string “dawn”, “morning”, “afternoon”, “evening” or “night” depending on the time of the day.
·        Provide a method isMorning() that returns true if it is morning.
4.      Provide a test program that prompts the user for time values, creates an object and uses all methods.
5.      Provide documentation comments and your name in a comment.
 

Due Date

Submit all zipped files through blackboard.com no later than November 29 by 11:59 pm.
Item A7

>> View/Complete Assignment: A7
Item Solution
import java.text.DecimalFormat;  // used for number formatting
// This class maintains the time in 24-hour format
public class Time  {
   private int hour;     
   private int minute;   
   private int second;   
   public Time() { 
     setTime( 0, 0, 0 ); 
   }
   public Time( int h, int m, int s ) { 
     setTime( h, m, s ); 
   }
   public void setTime( int h, int m, int s ) {
       setHour( h );    
       setMinute( m );  
       setSecond( s );  
   }
   public void setHour( int h ) { 
     hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 
   }
   public void setMinute( int m ) { 
     minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
   }
   public void setSecond( int s ) { 
     second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 
   }
   public String toMilitary()
   {
      DecimalFormat twoDigits = new DecimalFormat( "00" );
      return twoDigits.format( hour ) + ":" +
             twoDigits.format( minute ) + ":" +
             twoDigits.format( second );
   }
   // Convert to String in standard-time format
   public String toString()
   {
      DecimalFormat twoDigits = new DecimalFormat( "00" );
      String str = "";
      
      str = ( hour == 12 || hour == 0 ) ? "12" : "" + (hour % 12);
      str = str + ":" + twoDigits.format( minute ) + ":" +
             twoDigits.format( second );
      
      str = str +  ( hour < 12 ? " AM" : " PM" );
      return str;
   }
   
   public String timeOfDay(){
     String str="";
     
     switch  ( hour ){
      case 1: case 2: case 3: case 4: case 5: 
       str = "dawn";
       break;
      case 6: case 7: case 8: case 9: case 10: case 11:
       str = "morning";
       break;
      case 12:
       str = "noon";
       break;
      case 13: case 14: case 15: case 16: case 17:
       str = "afternoon";
       break;
      case 18: case 19:
       str = "evening";
       break;
      default:
       str = "night";
      }
      
     return str;
    }
   public boolean isMorning(){
     return hour > 6 && hour < 12;
   }
   public boolean isMidday(){
     return hour == 12;
   }
   public boolean isEvening(){
     return hour > 18 && hour < 20;
   }   
}
import javax.swing.JOptionPane;
public class TimeTest {
   public static void main( String [] args )
   {
      Time t;
      String hour = JOptionPane.showInputDialog("Enter hour ");
      String minute = JOptionPane.showInputDialog("Enter minutes ");
      String second = JOptionPane.showInputDialog("Enter seconds ");
      
      t = new Time(Integer.parseInt(hour), Integer.parseInt(minute), Integer.parseInt(second) );
     System.out.println( "Military time: " + t.toMilitary() );
     System.out.println( "Standard time: " + t.toString() );
     System.out.println( "Time of Day: " + t.timeOfDay() );
     System.exit(0);
   }
}

OK

Implement a class RoachPopulation that simulates the growth of a population of roaches. Provide an application to run the simulation.

CS 120 Assignment # 6

Objective

Implement a class RoachPopulation that simulates the growth of a population of roaches.  Provide an application to run the simulation.

Project Specifications

1.                  The class RoachPopulation keeps track of the size of the population of roaches.
2.                  The constructor takes the size of the initial roach population.
3.                  Overload the constructor to allow for a default initial value.
4.                  Provide a method breed to simulate a period where the population doubles. 
5.                  Provide a method spray to simulate spraying with insecticide.  When we call this method, the population will automatically be reduced by 10%.
6.                  Provide a method getRoaches() that returns the current value for the population of roaches.
7.                  Provide a program called RoachSimulation to simulate a kitchen that starts out with some roaches.
8.                  Breed, spray and then print the roach count.  Repeat several times.
9.                  Please use comments to display your name, date and assignment number.
10.       Provide documentation comments for your class RoachPopulation.  Make sure JavaDoc produces a usable documentation file.

Final Touches

Submit both java files ZIPPED through blackboard no later than November 18 by 11:59 pm. 
Item A6

>> View/Complete Assignment: A6
Item Solution
public class RoachPopulation
{
   /**
      Constructs the population.
      @param initialPopulation the initial population
   */
   public RoachPopulation(int initialPopulation)
   {
      roaches = initialPopulation;
   }
   /**
      Waits for the population to double.
   */
   public void breed()
   {
      roaches = 2 * roaches;
   }
   /**
      Simulates applying of insecticide.
   */
   public void spray()
   {
      roaches = roaches * 9 / 10;     
   }
   /**
      Gets the current number of roaches.
      @return the roach count
   */
   public int getRoaches()
   {
      return roaches;
   }
   private int roaches;
}
/**
   This program tests the RoachPopulation class.
*/
public class ExP2_16

   public static void main(String[] args)
   { 
      RoachPopulation kitchen = new RoachPopulation(10);
      kitchen.breed();
      kitchen.spray();
      System.out.println(kitchen.getRoaches() + " roaches");
      kitchen.breed();
      kitchen.spray();
      System.out.println(kitchen.getRoaches() + " roaches");
      kitchen.breed();
      kitchen.spray();
      System.out.println(kitchen.getRoaches() + " roaches");
      kitchen.breed();
      kitchen.spray();
      System.out.println(kitchen.getRoaches() + " roaches");
   }
}

OK 
 

Write an Application that will help an elementary school student learn multiplication.


Assignment5 - Loops
index.html (1.257 Kb)

Assignment #5

Objective

Computers are playing an increasing role in education.  Write an Application that will help an elementary school student learn multiplication.

Project Specifications

1.      Download the Multiplier class and its Help file (index.html) provided in Blackboard – Assignments – Assignment5 and save them in a new folder.
2.      Review the help to check for data, constructors, and all the methods available for this class.
3.      Provide an application called GameTester in the same folder where you placed the Multiplier class.
4.      Use comments to show your name, the date and the assignment number.
5.      Use the class Multiplier to generate a multiplication question and display it to the user.
6.      Prompt the user for the answer and check it. Display a message accordingly. 
7.      If the answer is correct congratulate the user and proceed to ask the user whether they want to play again.
8.      If the answer is incorrect display an encouraging message and let the user try again.
9.      Allow the user to try to get the correct answer 3 times.  After that display the correct answer and ask whether they want to play again.
10. Do NOT modify the Multiplier class.
11. Please make sure your program is indented correctly.
 

Due Date: 

Submit your *.java file through Blackboard no later than Nov 9 by 11:59 pm.

Item A5

>> View/Complete Assignment: A5
Item Solution
import java.util.*;
public class GameTester
{
 
  public static void main(String args[])
  {
    Multiplier game = new Multiplier();
    String again = "y";
    int answer = 0;
    int counter;
   
    Scanner scan = new Scanner(System.in);
   
    while ( again.equalsIgnoreCase( "y" ) )
    {
      System.out.println( game.nextQuestion() );
      answer = scan.nextInt();
     
      if ( game.isAnswer( answer ) )
        System.out.println ("Correct!!!");
      else
      {
        counter = 1;
        while ( !game.isAnswer( answer ) && counter <= 2 )
        {
          System.out.println ("Sorry, the answer is incorrect.  Try again.");
          System.out.println( game.getQuestion() );
          answer = scan.nextInt();
          counter++;
        }
        if (!game.isAnswer( answer ))
           System.out.println ("Sorry, the answer is incorrect.  The answer is " + game.getAnswer() );
        else
          System.out.println ("Correct!!!");
      }
      System.out.println("Would you like to play again?");
      again = scan.next();
    }
   
  }
}

import java.util.*;
/**
 A Multiplier object will generate a multiplication question. 
 */ 
public class Multiplier
{
  private int operand_1;
  private int operand_2;
  private int answer;
  private String question;
  private Random generator;
  /** 
   Constructs a Multiplier question with 2 operands and an answer. 
   */ 
  public Multiplier()
  {
    generator = new Random();
    operand_1 = getNumber();
    operand_2 = getNumber();
    answer = operand_1 * operand_2;
    question = "How much is " + operand_1 + " times " + operand_2 + " ?";
  }
  /** 
   Returns the answer to the generated question. 
   @return the answer 
   */
  public int getAnswer()
  {
    return answer;
  }
  /** 
   Returns the operand_1. 
   @return operand_1
   */
  public int getOperand_1()
  {
    return operand_1;
  }
  /** 
   Returns the operand_2. 
   @return operand_2
   */   
  public int getOperand_2()
  {
    return operand_2;
  }
  /** 
   Compare the guess to the question answer. 
   @param guess the users guess to the problem
   @return true if guess is correct false otherwise
   */      
  public boolean isAnswer( int guess )
  {
    if ( guess == answer ) 
      return true;
    else 
      return false;
  }
  /** 
   Constructs and returns a new multiplication question. 
   @return question
   */
  public String nextQuestion()
  {
    operand_1 = getNumber();
    operand_2 = getNumber();
    answer = operand_1 * operand_2;;
    question = "How much is " + operand_1 + " times " + operand_2 + " ?";
    return question;
  }
    /** 
   Returns the current multiplication question. 
   @return question
   */
  public String getQuestion()
  {
    return question;
  }
  /** 
   Returns random number . 
   @return operand
   */
  public int getNumber()
  {
    return generator.nextInt(11);
  }
  /** 
   Returns the multiplication question. 
   @return question
   */  
  public String toString()
  {
    return question;
  }  
}
 
 


Class Multiplier

java.lang.Object extended by Multiplier

public class Multiplier
extends Object
A Multiplier object will generate a multiplication question.
Constructor Summary
Multiplier()
          Constructs a Multiplier question with 2 operands and an answer.
 
Method Summary
 int getAnswer()
          Returns the answer to the generated question.
 int getNumber()
          Returns random number .
 int getOperand_1()
          Returns the operand_1.
 int getOperand_2()
          Returns the operand_2.
 String getQuestion()
          Returns the current multiplication question.
 boolean isAnswer(int guess)
          Compare the guess to the question answer.
 String nextQuestion()
          Constructs and returns a new multiplication question.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Constructor Detail

Multiplier

public Multiplier()
Constructs a Multiplier question with 2 operands and an answer.
Method Detail

getAnswer

public int getAnswer()
Returns the answer to the generated question.
Returns:
the answer

getOperand_1

public int getOperand_1()
Returns the operand_1.
Returns:
operand_1

getOperand_2

public int getOperand_2()
Returns the operand_2.
Returns:
operand_2

isAnswer

public boolean isAnswer(int guess)
Compare the guess to the question answer.
Parameters:
guess - the users guess to the problem
Returns:
true if guess is correct false otherwise

nextQuestion

public String nextQuestion()
Constructs and returns a new multiplication question.
Returns:
question

getQuestion

public String getQuestion()
Returns the current multiplication question.
Returns:
question

getNumber

public int getNumber()
Returns random number .
Returns:
operand


 

OK

Using Classes and Objects

Using Classes and Objects
Car.java (1.499 Kb)
index.html (1.243 Kb)

Assignment #4

Objective

In this assignment you will create a test program that uses the class Car provided to you.  Your test program will create Car objects and manipulate them. 

Project Specifications

1.      Download the Car class provided above and save it in a new folder.
2.      Start DrJava and open the class Car. 
3.      Click on the right-most button Javadoc and click ok when the Select Javadoc Destination window appears.  This utility will create the help documentation for Car class and save it in your folder.
4.      Review the help to check for data, constructors, and all the methods available for this class.
5.      Provide an application called CarTester in the same folder where you placed the Car class.
6.      Use comments to show your name, the date and the assignment number.
7.      Create at least two different car objects by using each constructor once.
8.      Print each object after it is created to display its state.
9.      Use each method provided by the class at least once per object. 
10. Make sure you print the object each time you change the state.
11. Manipulate the cars so that in the end they all have travelled a distance of 1000 miles.  
12. Display which car uses the least amount of gas (is more efficient).
13. Do NOT modify the Car class.

Due Date: 

Submit your *.java file through Blackboard no later than Oct 26 by 11:59 pm.

Item A4

>> View/Complete Assignment: A4
Item Solution
/**
   This program tests the Car class.
*/
public class CarTest
{
   public static void main(String[] args)
   {
      Car c1 = new Car(50, 0);
      Car c2 = new Car();
     
      System.out.println("Car 1 has " + c1.getMileage() + " miles and " + c1.getGas() + " gallons of gas." );
     
      c1.pumpGas( 100 );
      System.out.println("Car 1 has " + c1.getMileage() + " miles and " + c1.getGas() + " gallons of gas." );
      c1.drive(500);
      System.out.println("Car 1 has " + c1.getMileage() + " miles and " + c1.getGas() + " gallons of gas." );
      c1.drive(500);
      System.out.println("Car 1 has " + c1.getMileage() + " miles and " + c1.getGas() + " gallons of gas." );
     
      System.out.println("\nCar 2 has " + c2.getMileage() + " miles and " + c2.getGas() + " gallons of gas." );
     
      c2.pumpGas( 100 );
      System.out.println("Car 2 has " + c2.getMileage() + " miles and " + c2.getGas() + " gallons of gas." );
      c2.drive(500);
      System.out.println("Car 2 has " + c2.getMileage() + " miles and " + c2.getGas() + " gallons of gas." );;
      c2.drive(500);
      System.out.println("Car 2 has " + c2.getMileage() + " miles and " + c2.getGas() + " gallons of gas." ); 
     
      System.out.println("Both cars have travelled 1000 miles.  The most efficienct car has " + Math.max(c1.getGas(), c2.getGas()) + " gas.");
     
      if ( c1.getGas() > c2.getGas() )
      System.out.println("The most efficient car is Car 1");
      else if  ( c1.getGas() < c2.getGas() )
       System.out.println("The most efficient car is Car 2");    
       else
       System.out.println("They both have same efficiency");    
   }
}









Car.java (class)
/**
 A car can drive and consume fuel based on its efficiency. 
 */ 
public class Car {
  private int mileage;
  private int gas;
  private double efficiency;
  /** 
   Constructs a car with a given fuel efficiency. 
   */ 
  public Car()
  {
    efficiency = 15;
    mileage = 0;
    gas = 0;
  }
  /** 
   Constructs a car with a given fuel efficiency and some gas. 
   @param anEfficiency the fuel efficiency of the car 
   @param igas initial amount of gas in the car 
   */ 
  public Car(double anEfficiency, int igas) 
  {
    efficiency = anEfficiency;
    mileage = 0;
    gas = igas;
  }
  /** Adds a certain amount of gas to the tank. 
    @param amount the amount of fuel to add 
    */
  public void pumpGas( int amount) { 
    gas += amount; 
  }
  /** 
   Returns the amount of gas left in the tank. 
   @return the amount of gas 
   */  
  public int getGas(){ 
    return gas; 
  }
  /** 
   Returns the amount of miles the car has driven. 
   @return the mileage 
   */  
  public int getMileage(){
    return mileage;
  }
  /** 
   Drives a certain distance and consumes gas. 
   @param distance the distance driven 
   */ 
  public void drive( int distance ){
    mileage += distance;
    gas -= distance/efficiency;
  } 
/** 
   Returns the state of the object. 
   @return the state of the object as a string 
   */  
  public String toString(){ 
    return " Car: [ efficiency = " + efficiency + " gas = " + gas + " mileage = " + mileage; 
  }  
} 
 


Class Car

java.lang.Object extended by Car

public class Car
extends Object
A car can drive and consume fuel based on its efficiency.




Constructor Summary
Car()
          Constructs a car with a given fuel efficiency.
Car(double anEfficiency, int igas)
          Constructs a car with a given fuel efficiency and some gas.
 
Method Summary
 void drive(int distance)
          Drives a certain distance and consumes gas.
 int getGas()
          Returns the amount of gas left in the tank.
 int getMileage()
          Returns the amount of miles the car has driven.
 void pumpGas(int amount)
          Adds a certain amount of gas to the tank.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Constructor Detail

Car

public Car()
Constructs a car with a given fuel efficiency.

Car

public Car(double anEfficiency, int igas)
Constructs a car with a given fuel efficiency and some gas.
Parameters:
anEfficiency - the fuel efficiency of the car
igas - initial amount of gas in the car
Method Detail

pumpGas

public void pumpGas(int amount)
Adds a certain amount of gas to the tank.
Parameters:
amount - the amount of fuel to add

getGas

public int getGas()
Returns the amount of gas left in the tank.
Returns:
the amount of gas

getMileage

public int getMileage()
Returns the amount of miles the car has driven.
Returns:
the mileage

drive

public void drive(int distance)
Drives a certain distance and consumes gas.
Parameters:
distance - the distance driven


 

In this assignment you will write an application that generates computer usernames and email addresses for our college

Objective

In this assignment you will write an application that generates computer usernames and email addresses for our college MassBay.edu .  

Project Specifications

1.      Provide a test program called Assignment3.
2.      Use comments to show your name, the date and the assignment number.
3.      Request a user’s first name and last name and create a username using the following rules:
a.      The username should be all lower case.
b.      Use the first letter of the first name followed by an underscore (_) and
c.      The first 5 letters of the last name (the user’s last name must be at least 5 letters).
d.      Followed by a randomly generated 3-digit number.
4.      Create an email address by combining the username and the school’s domain name. 
5.      Display a nice message for the user with their original name, the new username and the new email address.

Due Date: 

Submit your *.java file through Blackboard no later than October 14 by 11:59 pm.

IMPORTANT SUBMISSION INSTRUCTIONS: 

1.      In blackboard click on AssignmentsAssignment3 – at the bottom of the document click on View/Complete Assignment: A3 to upload your file.
2.      Use the BROWSE button to find the file.   Select it and click on the Submit button.
Start early and if you have trouble with this assignment PLEASE come to see me!
Item A3

>> View/Complete Assignment: A3
Item Solution
import java.util.Scanner;
import java.util.Random;
import java.text.DecimalFormat;
public class Username2
{
  //-----------------------------------------------------------------
  //  Produces a username based on the user's first and last names.
  //  Assumes the last name is at least five characters long
  //-----------------------------------------------------------------
  public static void main (String[] args)
  {
    String first, last, username, email;
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();
   
    System.out.print ("Enter your first name: ");
    first = scan.nextLine();
    System.out.print ("Enter your last name: ");
    last = scan.nextLine();
   
    //username = first.charAt(0) + last.substring(0, 5) +
   //  (rand.nextInt(900) + 100);  
    //   OR
    DecimalFormat fmt = new DecimalFormat("000");
    username = first.charAt(0) + last.substring(0, 5) + fmt.format( (rand.nextInt(1000) ));
    username = username.toLowerCase();
    email = username + "@massbay.edu";
   
    System.out.println("Dear " + first + " " + last + "\nyour Username is: " +
                         username + "\nyour email address is: " + email);
 
  }
}

OK