Spring Semester 2004


Lab Notes Two: Sample problems. The solutions.

Here are examples of solutions, I skip the statement, I write only the sample solutions.

/******************************************************************************

  This is the solution to the first problem in the first problem set. Note 
  that you need ConsoleReader, which is available from the second set of lab 
  notes (Lab Two) off the class notes page or from the book. Once you get the 
  Consolereader class off the web notes place it in a file of its own, with 
  the name ConsoleReader.java in the same directory with Two.java and whose 
  source code is written below, then compile Two.java. 

*******************************************************************************/

class One {
    public static void main(String[] args) { 

	ConsoleReader console = new ConsoleReader(System.in); 

	System.out.print("Please enter your first integer number, ");  
	System.out.println("then press Enter.");

	int n1 = console.readInt(); 

	System.out.print("Please enter your second integer number, ");  
	System.out.println("then press Enter.");

	int n2 = console.readInt(); 

	int sum = n1 + n2; 
	System.out.println(n1 + " + " + n2 + " = " + sum); 

	int diff = n1 - n2; 
	System.out.println(n1 + " - " + n2 + " = " + diff); 

	int prod = n1 * n2; 
	System.out.println(n1 + " * " + n2 + " = " + prod); 

	double avg = sum / 2.0; 
	System.out.println("avg(" + n1 + ", " + n2 + ") = " + avg);

	int dist = Math.abs(n1 - n2); 
	System.out.println("dist(" + n1 + ", " + n2 + ") = " + dist); 


	long max = Math.round(avg + dist / 2.0); 
        // neat trick; can you explain it? 

	System.out.println("max(" + n1 + ", " + n2 + ") = " + max); 


	long min = Math.round(avg - dist / 2.0); 
        // neat trick; can you explain it? 

	System.out.println("min(" + n1 + ", " + n2 + ") = " + min); 
          

    } 
}
/*****************************************************************************

  This is the solution to the second problem in Lab Notes Two. ConsoleReader 
  is needed, use it as described in problem 2. This is a typical problem in 
  which you carefully need to cover roundoff errors so use Math.round after 
  you transform the problem in whole units (cents). 

******************************************************************************/ 

class Two {
    public static void main(String[] args) {

	// get a connection to the keyboard 
	ConsoleReader console = new ConsoleReader(System.in); 

	// ask the user for the amount due 
	System.out.println("Type the amount due then press enter."); 
	// read it 
	double due = console.readDouble(); 

	// ask the user for the amount received 
	System.out.println("Type the amount received then press enter."); 
	// read it 
        double received = console.readDouble(); 

	// assume received is bigger than due and compute difference 
	double difference = (received - due); 
	// you need to return this as change so make it a whole number
	// of cents regardless of how many decimals the user has entered  
  	int diff = (int)(Math.round(difference * 100)); 

	// tell the user what change you are processing 
	System.out.println("Give " + diff / 100.00 + " in change as follows: "); 

	// number of quarters; integer division 
	int quarters = diff / 25; 
	// report it 
	System.out.println("   " + quarters + " quarters"); 

	// adjust the remaining change (modulo) 
	diff = diff % 25;

	// compute the number of dimes
	int dimes = diff / 10; 
	// report it 
	System.out.println("   " + dimes + " dimes"); 

	// adjust remaining cents (notice shortcut operator) 
	diff %= 10; // notice anything compared to the previous assignment? 

	// these are the cents 
	int cents = diff; 
	// report them too 
	System.out.println("   " + cents + " cents"); 


    } 
}


/**********************************************************************

  This is the solution to the third problem in Lab Notes Three.
  Need ConsoleReader in the same directory before you can compile 
  it (see Lab Notes Two). Formulas used are straightforward, easy. 

***********************************************************************/ 

class Three {
    public static void main(String[] args) {

	// get a connection to the keyboard 
	ConsoleReader console = new ConsoleReader(System.in); 

	// greet the user, ask for number of gallons 
	System.out.println("Please enter the number of gallons then press enter.");
	// read number of gallons
	double gallons = console.readDouble(); 

	// ask for fuel efficiency
	System.out.println("Please enter the fuel efficiency " + 
                           "(miles/gallon) then press enter. "); 
	// read user input  
	double efficiency = console.readDouble(); 

	// ask for price per gallon 
	System.out.println("Please enter the price per gallon, then press enter."); 
	// read price from user 
	double price = console.readDouble(); 

	// computer how far the user can go with that much gas 
	double howFar = efficiency * gallons; 

	// compute how much that will cost 
	double totalCost = price * gallons; 

	// divide this by howFar and multiply by 100 to get price per 100 miles 
	double pricePer100Miles = totalCost / howFar * 100; 

	System.out.println("With the gas in the tank you can go " + 
			   howFar + " miles, \nat a cost of "     + 
                           pricePer100Miles + " per 100 miles."); 

    } 
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

  This is the solution to problem four in Lab Notes Two. You need to have 
  ConsoleReader in a file in the same directory before you can compile and run 
  this. This problem adds 24 hours to the hours difference to avoid negative values 
  and takes the remainder with 24 to avoid values bigger than 24 (number of hours 
  in a day). It also transforms the hours into minutes to absorb possible negative 
  values from the difference between given minutes. 

 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 

class Four {
    public static void main(String[] args) {

	// get a connection to the keyboard 
	ConsoleReader console = new ConsoleReader(System.in); 

	// greet the user, ask for time 
	System.out.print("Please enter the first time: "); 
	// get the first time as a string (in military format)
	String first = console.readLine(); 

	// compute the number of hours from first two characters 
	int hours1 = Integer.parseInt(first.substring(0, 2)); 
	// compute minutes from next two characters 
	int minutes1 = Integer.parseInt(first.substring(2, 4)); 

	// ask for second time
	System.out.print("Please enter the second time: "); 
	// get it 
	String second = console.readLine(); 

	// compute hours, same as before 
	int hours2 = Integer.parseInt(second.substring(0, 2)); 
	// compute minutes 
	int minutes2 = Integer.parseInt(second.substring(2, 4)); 

	// compute the difference between hours, add 24 then divide
        // by 24 and take the remainder to express the hour difference 
	int difHours  = (hours2 + 24 - hours1) % 24; 
	// make these hours into minutes 
	int hrsToMins = difHours * 60; 
	// compute straight difference between given minutes, could be < 0
	int difMins   = minutes2 - minutes1; 
	// add this to total count of minutes 
	hrsToMins    += difMins; 

	// report total count of minutes in hours and minutes 
	System.out.println(
          hrsToMins / 60 + " hours " + hrsToMins % 60 + " minutes"
        ); 

    } 
}


/*******************************************************************************

  This is the solution to problem number five in the first problem set. 
  The program attempts to use a different way of computing the average of 
  two numbers a and b by computing (1/a + 1/b)*a*b/2 in stages. It is OK if 
  the numbers entered are restricted to integers, but to correctly compute
  at all stages in the program we need to circumvent integer division which
  can result in a loss of precision. So we turn everything in float and all
  is well after that. You need ConsoleReader as explained above. 

********************************************************************************/ 


class Five { 
    public static void main(String[] args) {
	ConsoleReader console = new ConsoleReader(System.in);
	// one change below 
	float total = 0;
	System.out.println("Please enter a positive number:");
	// second change below 
	float x1 = (float)Integer.parseInt(console.readLine());
	System.out.println("total = " + total);
	total = total + 1 / x1;
	System.out.println("total = " + total);
	System.out.println("Please enter a positive number:");
	// third change below 
	float x2 = (float)Integer.parseInt(console.readLine());
	total = total + 1 / x2;
	System.out.println("total = " + total);
	total = total * x1 * x2 / 2;
	System.out.println("total = " + total);
	System.out.println("The average is " + total);
	// that's it, three changes overall
    }
}


/***********************************************************************************

  Solution to problem six in the first problem set. Use ConsoleReader from lab 
  notes as explained in problem set 2. The trick here (as hinted in the text) is 
  to transform a number for a month in the position in the string where the month 
  name is starting, all names being made of the same length, and then concatenated 
  together in one final string. 

************************************************************************************/ 

class Six { 
    public static void main(String[] args) {

	String monthNames = "January   " +
                            "February  " +
                            "March     " +
                            "April     " +
                            "May       " +
                            "June      " +
                            "July      " +
                            "August    " +
      	                    "September " + // longest
                            "October   " +
                            "November  " +
                            "December  "    ;

	// open a connection with the keyboard 
	ConsoleReader console = new ConsoleReader(System.in); 

	// greet the user, and ask for input 
	System.out.println("Please enter a month number from 1 to 12."); 
	// get month name 
	int month = console.readInt(); 
	// report the name of the month 
	System.out.println(
            monthNames.substring("September ".length() * (month-1), 
                                 "September ".length()*month));

	// formula uses the length of the longest name 
    }
}


Last updated: Jan 23, 2004 by Adrian German for A201