Assignment # 8

Due May 8th (before class starts)

From the textbook:

Solutions

Motorboat.java

import java.util.Scanner;

public class MotorBoat {


    private double tankCapacity;
    private double fuelInTank;
    private double maxSpeed;
    private double currentSpeed;
    private double motorEfficiency;
    private double distanceTraveled;



    public void initialize(double capacityOfTank, double maximumSpeed, double efficiency) {
        tankCapacity = capacityOfTank;
        fuelInTank = 0.0;
        maxSpeed = maximumSpeed;
        currentSpeed = 0.0;
        motorEfficiency = efficiency;
        distanceTraveled = 0.0;
    }



    public void changeSpeed(double newSpeed){
        if(newSpeed < 0.0)
            currentSpeed = 0.0;
        else if (newSpeed > maxSpeed)
            currentSpeed = maxSpeed;
        else
            currentSpeed = newSpeed;
    }

    public void operateForTime(double time){

        if(time > 0.0 ){
            double fuelUsage = motorEfficiency * currentSpeed * currentSpeed * time;

            double realTime;

            // Determine if we run out of fuel
            if(fuelUsage > fuelInTank){
                realTime = time * (fuelInTank/fuelUsage);
                fuelInTank = 0.0;
            }else{
                fuelInTank -= fuelUsage;
                realTime = time;
            }
            distanceTraveled += currentSpeed * realTime;
        }

    }

    public void refuelBoat(double amount){
        if(amount > 0.0){
            if (amount + fuelInTank > tankCapacity)
                fuelInTank = tankCapacity;
            else
                fuelInTank += amount;
        }
    }

    public double fuelRemaining(){
        return fuelInTank;
    }

    public double distance(){
        return distanceTraveled;
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        MotorBoat myBoat = new MotorBoat();
        myBoat.initialize(5.0, 55.0, 0.001);

        System.out.println("We are trying to travel for 1.0 hour with no fuel.");
        myBoat.operateForTime(1.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();

        System.out.println("trying to add 10 gallons of fuel.");
        System.out.println("But should only be able to hold 5.");
        myBoat.refuelBoat(10.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();


        System.out.println("We are traveling for 1.0 hour with a speed of 0.");
        myBoat.operateForTime(1.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();

        System.out.println("Trying to change the speed to 85.");
        System.out.println("Should only be able to go 55.");
        myBoat.changeSpeed(85.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();

        System.out.println("We are traveling for 1.0 hour with a speed of 55.");
        System.out.println("Should use 3.025 gallons of fuel and travel 55 miles.");
        myBoat.operateForTime(1.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();

        System.out.println("We are traveling for 2.0 hours with a speed of 45.");
        System.out.println("Should use all 1.975 remaining gallons.  " +
                "The travel time will be 0.9753 and the distance is approximately 43.888 miles");
        myBoat.changeSpeed(45.0);
        myBoat.operateForTime(2.0);
        System.out.println("Fuel left is " + myBoat.fuelRemaining()
        + " and we have gone " + myBoat.distance());
        System.out.println();



    }

}

Counter.java

public class Counter
{
    private int value;

    /**
     Sets the counter to zero
    */

    public void setZero()
    {
        value = 0;
    }

    /**
     Increment counter by one
    */

    public void increment()
    {
        value++;
    }

    /**
     Decrements value by one, but does not go below zero
    */

    public void decrement()
    {
        if(value > 0)
            value--;
    }

    /**
     Returns the counter's value.
    */

    public int countIs()
    {
        return value;
    }

    /**
     Displays the counter's value.
    */

    public void printCounter()
    {
        System.out.println("Counter value = " + value);
    }
 }

Assignment # 7

Due April 13th (before class starts)

  1. Print out the following two structures, based on how many lines the user wants. For structure B the number of lines means the lines till the middle of the structure

Structure A:

        *
       ***
      *****
     *******

Structure B:

        *
       ***
      *****
     *******
      ***** 
       ***
        *

Solution

     System.out.println("Please enter a number for the lines you want structure A");
        Scanner kb = new Scanner (System.in);
        int n = kb.nextInt(); // n is the number of lines       

        for (int i = 1; i <= n; i++) {

            // print out the blanks
            for (int k = 1; k <= n-i; k++) {
                System.out.print(" ");
            }

            // print out the asterisks
            for (int j = 0; j < 2*i-1; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }


        System.out.println("Please enter a number for the lines you want structure B");
        int m = kb.nextInt(); // n is the number of lines       

        // print the top
        for (int i = 1; i <= m; i++) {          
            // print out the blanks
            for (int k = 1; k <= m-i; k++) {
                System.out.print(" ");
            }           
            // print out the asterisks
            for (int j = 0; j < 2*i-1; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }

        // print the bottom
        for (int i = 1; i <= m-1; i++) {
            // print out the blanks
            for (int k = 1; k <= i; k++) {
                System.out.print(" ");
            }
            // print out the asterisks
            for (int j = 1; j <= 2*(n-i)-1; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
  1. Programming Project 9 from the textbook (pg. 232)

Solution

    System.out.println("Please enter a word to check for reversibility");
    Scanner kb = new Scanner (System.in);

    String inputWord = kb.nextLine();
    while (!inputWord.equals("quit")) {

        /**
        * Basically, we need to figure out if after the removing the first character
        * we get same string by both reading backward and forward
        */
        int wordLength = inputWord.length();
        boolean foundMatch = true; // our deciding boolean is false iniitally

        // start counting characters
        for (int i=1; i < inputWord.length(); i++) { // 1 means we are neglecting the first character
            /**
            * if at any time the corresponding front and end characters don't match
            * then falsify our boolean value
            */ 
            if (inputWord.charAt(i) != inputWord.charAt(wordLength - i))
                foundMatch = false; 
        }
        if (foundMatch)
            System.out.println(inputWord + " has the reversible quality");
        else
            System.out.println(inputWord + " does not have the reversible quality");

        // read in a new word
        System.out.println("Please enter a word to check for reversibility");           
        inputWord = kb.nextLine();

Assignment # 6

Due April 3rd (before class starts)

You need to calculate the sum of first 10 odd numbers—i.e. the sum 1+3+5+7+9+11+13+15+17+19. You must do this by using:

  1. a while loop
  2. a for loop

In both cases, assume that you do not know what the final odd number (which is 19) will be. In other words, in your condition for the loop, you should not use 19 for the loop’s condition 1. You only know the starting odd number—1—and that the loop should add the 10 odd numbers.

Solution

Assignment # 5

Due March 12th (before 5 p.m.)

From Chapter 3:

  1. Exercises 2, 4, 5
  2. Programming Project 2

Solutions

Exercise 2.

    if(x % 2 == 1)
        x = 3*x - 1;
    else
        x = x/2;

Exercise 4.

a) B
b) B
c) A
d) A
e) A
f) A

Exercise 5.

a) C
b) C
c) A B
d) A B
e) A
f) A

Programming Project 2.

    // read in the numbers from the keyboard
    Scanner kb = new Scanner (System.in);
    int a = kb.nextInt();
    int b = kb.nextInt();
    int c = kb.nextInt();


    if(a < b && a < c)
    {

       System.out.println(a); // a is definitely the smallest
       if(b < c){
          System.out.println(b); // b is bigger than a but less than c
          System.out.println(c); // c is the smallest ... and so on ...
       }
       else{
          System.out.println(c);
          System.out.println(b);
          }
    }
    else if(b < a && b < c)
    {
       System.out.println(b);
       if(a < c){
          System.out.println(a);
          System.out.println(c);
          }
       else{
          System.out.println(c);
          System.out.println(a);
          }
    }
    else
    {
       System.out.println(c);
       if(a < b){
          System.out.println(a);
          System.out.println(b);
          }
       else{
          System.out.println(b);
          System.out.println(a);
          }
    }

Assignment # 4

Due March 9th (before 11 p.m.)

The corner grocer, Oddman Outré, has a thing for odd numbers: he hates giving out change that is an even number. So if you buy 86 cents worth of groceries (yeah, this is an old-timey tale) and hand him 120 cents, he has to give you … 34 cents back, an even number. This is a tragedy for poor Oddman and he will say to you: “Why would you do this to me?” If on the other hand he has to hand you back an odd number in change, he will say: “That’s mighty gracious of you!”

So…. write a program that will take in two integer values from the keyboard for purchase amount and the amount given to Oddman, and store them in variables purchaseAmount and amountGiven respectively. Next, declare a String variable oddManSays, and based on what we know about Oddman, give oddManSays the value "Why would you do this to me?" or "That's mighty gracious of you!".

Solution

    // read in the two amounts
    Scanner kb = new Scanner(System.in);
    int purchaseAmount = kb.nextInt();
    int amountTendered = kb.nextInt();

    // set up the String variable
    String oddManSays;

    // check if the amount to be handed back to the customer is even or not
    // we can do this by checking for the remainder after division by 2 
    if ((purchaseAmount - amountTendered) % 2 == 0 ) 
        oddManSays = "Why would you do this to me?";    
    else
        oddManSays = "That's mighty gracious of you!";

    System.out.println(oddManSays);

Assignment # 3

Due Feb. 23rd (before lecture)

  1. Write a program that creates a String variable—let’s call it message—and assign it any String you would like (some examples: "How is the weather?", "Hello, my name is Raheel"). Then using String methods (like length(); look for more methods on page 78 of textbook) find and print out the following:
    1. the number of characters in the string
    2. the characters in the string at positions 0, 3, and 5
    3. an all-upper case version of your original string
  2. Programming Exercise 4
  3. Programming Exercise 5

Solutions

  1. Class StringProcessor.java does the three tasks:

        public class StringProcessor {
            public static void main(String[] args) {
                String message = "How is the weather today?";
    
                // 1. find the number of characters in the String
                int numberOfCharacters = message.length();
                System.out.println("number of characters in \"" + message + "\" is: " + numberOfCharacters);
    
                // 2. characters at the 3 positions
                char characterOne = message.charAt(0);
                System.out.println("character at position 0 is: " + characterOne);
                char characterTwo = message.charAt(3);
                System.out.println("character at position 3 is: " + characterTwo);
                char characterThree = message.charAt(5);
                System.out.println("character at position 5 is: " + characterThree);
    
                // 3. upper case version of the String
                String upperCaseMessage = message.toUpperCase();
                System.out.println("upper case version is: " + upperCaseMessage);
    
            }
        }
    
  2. Exercise 4:

  1. Exercise 5: changes to ChangeMaker

    import java.util.Scanner;
    public class ChangeMaker {
        public static void main(String[] args) {
    
            int amount, originalAmount,
                    quarters, dimes, nickels, pennies;
    
            int dollars, halfDollars;
    
            //System.out.println("Enter a whole number from 1 to 99.");
            System.out.println("Enter a whole number greater than 0.");
            System.out.println("I will find a combination of coins");
            System.out.println("that equals that amount of change.");
    
            Scanner keyboard = new Scanner(System.in);
            amount = keyboard.nextInt();
    
            originalAmount = amount;
    
            dollars = amount / 100;
            amount = amount % 100;
    
            halfDollars = amount / 50;
            amount = amount % 50;
    
            quarters = amount / 25;
            amount = amount % 25;
            dimes = amount / 10;
            amount = amount % 10;
            nickels = amount / 5;
            amount = amount % 5;
            pennies = amount;
            System.out.println(originalAmount +
                    " cents in coins can be given as:");
            System.out.println(dollars + " dollars");
            System.out.println(halfDollars + " halfDollars");
            System.out.println(quarters + " quarters");
            System.out.println(dimes + " dimes");
            System.out.println(nickels + " nickels and");
            System.out.println(pennies + " pennies");
        }
    }
    

Assignment # 2

Due Feb. 18th (before lecture, 9a.m.)


  1. You can use 19 if you can’t figure out how to do without it.