Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
DAVID PEREZ
CSE 292
Homework 24
1) ( 10 Points ) TIme2
// Lab 1: Time2.java
// Time2 class definition with methods tick, 
// incrementMinute and incrementHour.
public class Time2
{
   private int hour; // 0 - 23
   private int minute; // 0 - 59
   private int second; // 0 - 59
   // Time2 no-argument constructor: initializes each instance variable 
   // to zero; ensures that Time2 objects start in a consistent state
   public Time2()
   {
      this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
   } // end Time2 no-argument constructor
   // Time2 constructor: hour supplied, minute and second defaulted to 0
   public Time2( int h ) 
   { 
      this( h, 0, 0 ); // invoke Time2 constructor with three arguments
   } // end Time2 one-argument constructor
   // Time2 constructor: hour and minute supplied, second defaulted to 0
   public Time2( int h, int m ) 
   { 
      this( h, m, 0 ); // invoke Time2 constructor with three arguments
   } // end Time2 two-argument constructor 
   // Time2 constructor: hour, minute and second supplied
   public Time2( int h, int m, int s ) 
   { 
      setTime( h, m, s ); // invoke setTime to validate time
   } // end Time2 three-argument constructor 
   // Time2 constructor: another Time2 object supplied
   public Time2( Time2 time )
   {
      // invoke Time2 constructor with three arguments
      this( time.getHour(), time.getMinute(), time.getSecond() );
   } // end Time2 constructor with Time2 argument
   // Set a new time value using universal time. Perform 
   // validity checks on data. Set invalid values to zero.
   /* Write header for setTime. */
public void setTime(int h, int m, int s)
   {
      /* Write code here that declares three boolean variables which are 
         initialized to the return values of setHour, setMinute and setSecond.
         These lines of code should also set the three member variables. */
setHour(h);
setMinute(m);
setSecond(s);
      /* Return true if all three variables are true; otherwise, return false. */
   }
   // validate and set hour
   /* Write header for the setHour method. */
   public void setHour(int h)
{
      /* Write code here that determines whether the hour is valid.
         If so, set the hour and return true. */
/* If the hour is not valid, set the hour to 0 and return false. */
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
      
   }
   // validate and set minute
   /* Write the header for the setMinute method. */
public void setMinute(int m)
{
      /* Write code here that determines whether the minute is valid.
         If so, set the minute and return true. */
      /* If the minute is not valid, set the minute to 0 and return false. */
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); 
  
}
   // validate and set second
   /* Write the header for the setSecond method. */
public void setSecond(int s)
{
      /* Write code here that determines whether the second is valid.
         If so, set the second and return true. */
      /* If the second is not valid, set the second to 0 and return false. */
second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 
   }
   // Get Methods
   // get hour value
   public int getHour() 
   { 
      return hour; 
   } // end method getHour
   // get minute value
   public int getMinute() 
   { 
      return minute; 
   } // end method getMinute
   // get second value
   public int getSecond() 
   { 
      return second; 
   } // end method getSecond
   // Tick the time by one second
   public void tick()
   {
      setSecond( second + 1 );
      if ( second == 0 )
         incrementMinute();
   } // end method tick
   // Increment the minute
   public void incrementMinute()
   {
      setMinute( minute + 1 );
      if ( minute == 0 )
         incrementHour();
   } // end method incrementMinute
   // Increment the hour
   public void incrementHour()
   {
      setHour( hour + 1 );
   } // end method incrementHour
   
   // convert to String in universal-time format (HH:MM:SS)
   public String toUniversalString()
   {
      return String.format( 
         "%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
   } // end method toUniversalString
   // convert to String in standard-time format (H:MM:SS AM or PM)
   public String toString()
   {
      return String.format( "%d:%02d:%02d %s", 
         ( ( getHour() == 0 || getHour() == 12 ) ? 12 : getHour() % 12 ),
         getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
   } // end method toStandardString
} // end class Time2
// Lab 1: Time2Test.java
// Program adds validation to Fig. 8.7 example
import java.util.Scanner;
public class Time2Test
{
   public static void main( String args[] )
   {
Scanner input = new Scanner( System.in );
      
Time2 time = new Time2(); // the Time2 object
int choice = getMenuChoice();
      
while ( choice != 5 )
{
switch ( choice )
{
            case 1: // set hour
System.out.print( "Enter Hours: " );
int hours = input.nextInt();
               
try 
{
time.setHour(hours);
}
catch (IllegalArgumentException e) {
System.out.printf("\nException while initializing Hours: 
%s\n", e.getMessage() );
}
/* Write code here that sets the hour. If the hour is invalid, 
                  display an error message. */
               
break;
           
            case 2: // set minute
               System.out.print( "Enter Minutes: " );
               int minutes = input.nextInt();
               try {
time.setMinute(minutes);
}
catch (IllegalArgumentException e) {
 System.out.printf("\nException while initializing Minutes: 
%s\n", e.getMessage() );
}
               /* Write code here that sets the minute. If the minute is invalid, 
                  display an error message. */
               break;     
    
            case 3: // set seconds
               System.out.print( "Enter Seconds: " );
               int seconds = input.nextInt();
try {
time.setSecond(seconds);
}
catch (IllegalArgumentException e) {
 System.out.printf("\nException while initializing Seconds: 
%s\n", e.getMessage() );
}
               
               /* Write code here that sets the second. If the second is invalid, 
                  display an error message. */
               break; 
            case 4: // add 1 second
               time.tick();               
               break;               
         } // end switch
         
         System.out.printf( "Hour: %d  Minute: %d  Second: %d\n",
            time.getHour(), time.getMinute(), time.getSecond() );
         System.out.printf( "Universal time: %s   Standard time: %s\n",
            time.toUniversalString(), time.toString() );
         choice = getMenuChoice();
      } // end while      
   } // end main
   // prints a menu and returns a value corresponding to the menu choice
   private static int getMenuChoice()
   {
      Scanner input = new Scanner( System.in );
      
      System.out.println( "1. Set Hour" );
      System.out.println( "2. Set Minute" );
      System.out.println( "3. Set Second" );
      System.out.println( "4. Add  second" );
      System.out.println( "5. Exit" );
      System.out.print( "Choice: " );
      
      return input.nextInt();
   } // end method getMenuChoice
} // end class Time2Test
I have finished the tasks successfully and assign a score of 10 points.
2) ( 10 Points ) Complex
// Lab 3: Complex.java
// Definition of class Complex
public class Complex
{
   private double real;
   private double imaginary;
   // Initialize both parts to 0
   /* Write header for a no-argument constructor. */
public Complex()
   { 
real = 0;
imaginary = 0;
      /* Write code here that calls the Complex constructor that takes 2 
         arguments and initializes both parts to 0 */
   } // end Complex no-argument constructor
public Complex(double realPart, double imaginaryPart){
real = realPart;
imaginary = imaginaryPart;
   // Initialize real part to r and imaginary part to i
   /* Write header for constructor that takes two arguments-real part r and
      imaginary part i. */
   }
   // Add two Complex numbers
   public Complex add( Complex right )
   {
Complex temp = new Complex(this.real, this.imaginary);
temp.real = this.real + right.real;
temp.imaginary = this.imaginary +right.imaginary;
return temp;
      /* Write code here that returns a Complex number in which the real part is
         the sum of the real part of this Complex object and the real part of the
         Complex object passed to the method; and the imaginary part is the sum 
         of the imaginary part of this Complex object and the imaginary part of 
         the Complex object passed to the method. */
   }
   // Subtract two Complex numbers
   public Complex subtract( Complex right )
   {
Complex temp = new Complex(this.real, this.imaginary);
temp.real = this.real - right.real;
temp.imaginary = this.imaginary - right.imaginary;
return temp;
      /* Write code here that returns a Complex number in which the real part is
         the difference between the real part of this Complex object and the real
         part of the Complex object passed to the method; and the imaginary part 
         is the difference between the imaginary part of this Complex object and
         the imaginary part of the Complex object passed to the method. */
   }
public double real() { return real; }
public double imaginary() { return imaginary; }
   // Return String representation of a Complex number
   public String toString() 
   { 
      return String.format( "(%.1f, %.1f)", real, imaginary );
   } // end method toComplexString;
} // end class Complex
// Exercise 8.12: ComplexTest.java
// Test the Complex number class
public class ComplexTest
{
   public static void main( String args[] )
   {
      // initialize two numbers
      Complex a = new Complex( 9.5, 7.7 );
      Complex b = new Complex( 1.2, 3.1 );
 
      System.out.printf( "a = %s\n", a );
      System.out.printf( "b = %s\n", b );
      System.out.printf( "a + b = %s\n", a.add( b ) );
      System.out.printf( "a - b = %s\n", a.subtract( b ) );
   } // end main
} // end class ComplexTest
Program run:
I have finished the tasks successfully and assign a score of 10 points.
3) ( 10 Points ) PayrollTest
// Lab Exercise 1: BasePlusCommissionEmployee.java
// BasePlusCommissionEmployee class extends CommissionEmployee.
public class BasePlusCommissionEmployee extends CommissionEmployee 
{
   private double baseSalary; // base salary per week
   // six-argument constructor
   public BasePlusCommissionEmployee( String first, String last, 
      String ssn, double sales, double rate, double salary )
   {
      super( first, last, ssn, sales, rate );
      setBaseSalary( salary ); // validate and store base salary
   } // end six-argument BasePlusCommissionEmployee constructor
   // set base salary
   public void setBaseSalary( double salary )
   {
      baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative
   } // end method setBaseSalary
   // return base salary
   public double getBaseSalary()
   {
      return baseSalary;
   } // end method getBaseSalary
   // calculate earnings; override method earnings in CommissionEmployee
   public double earnings()
   {
      return getBaseSalary() + super.earnings();
   } // end method earnings
   // return String representation of BasePlusCommissionEmployee object
   public String toString()
   {
      return String.format( "%s %s; %s: $%,.2f", 
         "base-salaried", super.toString(), 
         "base salary", getBaseSalary() );
   } // end method toString   
} // end class BasePlusCommissionEmployee
// Lab Exercise 1: Employee.java
// Employee abstract superclass.
public abstract class Employee 
{
   private String firstName;
   private String lastName;
   private String socialSecurityNumber;
   // three-argument constructor
   public Employee( String first, String last, String ssn )
   {
      firstName = first;
      lastName = last;
      socialSecurityNumber = ssn;
   } // end three-argument Employee constructor
   // set first name
   public void setFirstName( String first )
   {
      firstName = first;
   } // end method setFirstName
   // return first name
   public String getFirstName()
   {
      return firstName;
   } // end method getFirstName
   // set last name
   public void setLastName( String last )
   {
      lastName = last;
   } // end method setLastName
   // return last name
   public String getLastName()
   {
      return lastName;
   } // end method getLastName
   // set social security number
   public void setSocialSecurityNumber( String ssn )
   {
      socialSecurityNumber = ssn; // should validate
   } // end method setSocialSecurityNumber
   // return social security number
   public String getSocialSecurityNumber()
   {
      return socialSecurityNumber;
   } // end method getSocialSecurityNumber
   // return String representation of Employee object
   public String toString()
   {
      return String.format( "%s %s\nsocial security number: %s", 
         getFirstName(), getLastName(), getSocialSecurityNumber() );
   } // end method toString
   // abstract method overridden by subclasses
   public abstract double earnings(); // no implementation here
} // end abstract class Employee
// Lab Exercise 1: SalariedEmployee.java
// SalariedEmployee class extends Employee.
public class SalariedEmployee extends Employee 
{
   private double weeklySalary;
   // four-argument constructor
   public SalariedEmployee( String first, String last, String ssn, 
      double salary )
   {
      super( first, last, ssn ); // pass to Employee constructor
      setWeeklySalary( salary ); // validate and store salary
   } // end four-argument SalariedEmployee constructor
   // set salary
   public void setWeeklySalary( double salary )
   {
      weeklySalary = salary < 0.0 ? 0.0 : salary;
   } // end method setWeeklySalary
   // return salary
   public double getWeeklySalary()
   {
      return weeklySalary;
   } // end method getWeeklySalary
   // calculate earnings; override abstract method earnings in Employee
   public double earnings()
   {
      return getWeeklySalary();
   } // end method earnings
   // return String representation of SalariedEmployee object
   public String toString()
   {
      return String.format( "salaried employee: %s\n%s: $%,.2f", 
         super.toString(), "weekly salary", getWeeklySalary() );
   } // end method toString
} // end class SalariedEmployee
// Lab Exercise 1: HourlyEmployee.java
// HourlyEmployee class extends Employee.
public class HourlyEmployee extends Employee 
{
   private double wage; // wage per hour
   private double hours; // hours worked for week
   // five-argument constructor
   public HourlyEmployee( String first, String last, String ssn, 
      double hourlyWage, double hoursWorked )
   {
      super( first, last, ssn );
      setWage( hourlyWage ); // validate and store hourly wage
      setHours( hoursWorked ); // validate and store hours worked
   } // end five-argument HourlyEmployee constructor
   // set wage
   public void setWage( double hourlyWage )
   {
      wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;
   } // end method setWage
   // return wage
   public double getWage()
   {
      return wage;
   } // end method getWage
   // set hours worked
   public void setHours( double hoursWorked )
   {
      hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?
         hoursWorked : 0.0;
   } // end method setHours
   // return hours worked
   public double getHours()
   {
      return hours;
   } // end method getHours
   // calculate earnings; override abstract method earnings in Employee
   public double earnings()
   {
      if ( getHours() <= 40 ) // no overtime
         return getWage() * getHours();
      else
         return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;
   } // end method earnings
   // return String representation of HourlyEmployee object
   public String toString()
   {
      return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", 
         super.toString(), "hourly wage", getWage(), 
         "hours worked", getHours() );
   } // end method toString
} // end class HourlyEmployee
// Lab Exercise 1: CommissionEmployee.java
// CommissionEmployee class extends Employee.
public class CommissionEmployee extends Employee 
{
   private double grossSales; // gross weekly sales
   private double commissionRate; // commission percentage
   // five-argument constructor
   public CommissionEmployee( String first, String last, String ssn, 
      double sales, double rate )
   {
      super( first, last, ssn );
      setGrossSales( sales );
      setCommissionRate( rate );
   } // end five-argument CommissionEmployee constructor
   // set commission rate
   public void setCommissionRate( double rate )
   {
      commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
   } // end method setCommissionRate
   // return commission rate
   public double getCommissionRate()
   {
      return commissionRate;
   } // end method getCommissionRate
   // set gross sales amount
   public void setGrossSales( double sales )
   {
      grossSales = ( sales < 0.0 ) ? 0.0 : sales;
   } // end method setGrossSales
   // return gross sales amount
   public double getGrossSales()
   {
      return grossSales;
   } // end method getGrossSales
   // calculate earnings; override abstract method earnings in Employee
   public double earnings()
   {
      return getCommissionRate() * getGrossSales();
   } // end method earnings
   // return String representation of CommissionEmployee object
   public String toString()
   {
      return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", 
         "commission employee", super.toString(), 
         "gross sales", getGrossSales(), 
         "commission rate", getCommissionRate() );
   } // end method toString
} // end class CommissionEmployee
// Lab Exercise 1: PieceWorker.java
// PieceWorker class extends Employee.
public final class PieceWorker extends Employee 
{
   private double wage; // wage per piece output
   private double pieces;        // output for week
   // Constructor for class PieceWorker
   public PieceWorker( String first, String last, String ssn,
                       double wagePerPiece, double piecesProduced )
   {
      super( first, last, ssn );  // call superclass constructor
      setWage( wagePerPiece );
      setPieces( piecesProduced );
   }
   
   // Set the wage
   public void setWage( double wagedWork ) 
{ 
wage = wagedWork; 
}
public double getWage()
{
return wage;
}
   
   // Set the number of items output
   public void setPieces( double piecesMade ) 
{
 pieces = piecesMade;
}
public double getPieces()
{
return pieces;
}
   
   // Determine the PieceWorker's earnings
   public double earnings()
{ 
return getWage() * getPieces(); 
}
   
  // return String representation of PieceWorker object
public String toString()
{
return String.format("%s: %s\n%s: $%,.2f\n%s: %.2f", "Piecework Employee", 
super.toString(), "Wage is", getWage(), "Number of pieces", getPieces(), earnings() );
//Conversion character f will print at least one number to the right of the
//decimal
//Make sure the formating is the exact way you want it
//The spaces in the formatting will effect the way it prints out
}
// end method toString
}
// end
// Lab Exercise 1: PayrollSystemTest.java
// Employee hierarchy test program.
public class PayrollSystemTest 
{
   public static void main( String[] args ) 
   {
Employee employees[] = new Employee[5];
      // create subclass objects
      employees[0] = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
      employees[1] = new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );
      employees[2] = new CommissionEmployee( "Sue", "Jones", "333-33-3333", 10000, .06 );
      employees[3] = new BasePlusCommissionEmployee( "Bob", "Lewis", "444-44-4444", 5000, .04, 
300 );
 /* create a PieceWoker object and assign it to employees[ 4 ] */
employees[4] = new PieceWorker( "Omar" , " Laris", "555-55-5555", 99.99, 237);
      
System.out.println( "Employees processed polymorphically:\n" );
      
      // generically process each element in array employees
      for ( Employee currentEmployee : employees ) 
      {
         System.out.println( currentEmployee ); // invokes toString
         System.out.printf( 
            "earned $%,.2f\n\n", currentEmployee.earnings() );
      } // end for
   } // end main
} // end class PayrollSystemTes
Program Run:
I have finished the tasks successfully and assign a score of 10 points.
4) ( 10 Points ) Draw an inheritance hierarchy for students at a university
I have finished the tasks successfully and assign a score of 10 points.
5) ( 10 Points ) Reversing Digits
//ReversingDigits.java
import java.util.Scanner;
public class ReversingDigits
{
public int reverseDigits (int n )
{
// reverses a number
int r = 0;
while ( n != 0 )
{
r = r * 10 + n % 10; //makes r the new reverse digit
n = n / 10;         // find n minus the last number
}
return r;
}
public static void main(String [] args)
{
Scanner input = new Scanner( System.in );
System.out.println("Please enter a value:"); //prompts user for a number
int number;
number = input.nextInt();  //user input
ReversingDigits reverse = new ReversingDigits();   // creates new object
System.out.printf("Reversed Digits are: %s\n",
reverse.reverseDigits(number) );    //prints the new reversed digit
}//end main
}
// end class
Program Run:
I have finished the tasks successfully and assign a score of 10 points.
6) ( 10 Points ) Perfect Numbers
import java.util.*;
public class perfect
{
public static void main(String[] args) 
{
Scanner S=new Scanner(System.in);
System.out.print("Enter an integer : ");
int a=S.nextInt();
int b=a;
for(int i=1;a>0;i++)
{
a-=i;
}
if(a==0)
{
System.out.print(b+" is a perfect Number since "+b+" = ");
for(int i=1;a