Wednesday, September 23, 2009
Java Simple Program
Extend tax1 activity so that the program can handle a number of items larger than 1. Display pre-tax total, tax amount and total in a form of store receipt. The program still doesn't have to be interactive.
Exercise 2
You need to create a bill of sale for a computer store that sells PCs, printers, monitors, Hard Disks and RAM. Use the following prices :
PC $999.00
Printer $199.00
Monitor $399.00
RAM per Mb $0.20
HD per Gb $1.00
Ask the user how many of each they want to purchase. Assume that sales tax is 7.5%.
Interactive Session Example:
(prompt ‘>’ denotes output provided by your program (to distinguish it from user provided data – it should not be printed by your program) :
>How many PCs do you want to purchase ?
2
>How many printers do you want to purchase ?
3
>How many monitors do you want to purchase ?
2
>How many Mb of RAM do you need ?
64
>How many Gb of hard disk space do you need ?
4
>
> *****************
> * Bill of Sales *
> *****************
>
>Qty. Item Unit price Total price
>-------------------------------------------------------
> 02 PC $999.00 $1998.00
> 03 printer $199.00 $0597.00
> 02 monitor $399.00 $0798.00
> 64 RAM $004.00 $0256.00
> 04 HD $099.00 $0396.00
>-------------------------------------------------------
> Total without tax $4045.00
> Tax $0303.38
> Total with tax $4348.38
Note - the above represents just the form of your output. Numerical values are not necessarily correct.
It is important that your decimal points align.
Exercise 3
Write a program that solves quadratic equation. Given coefficients a, b and c, calculate solutions x1 and x2 according to the following formula:
Your program needs to correctly handle the following cases:
• coefficient a equal to 0
• discriminant equal to 0
• discriminant less than 0
________________________________________
Example 1:
>Enter a:
1
>Enter b:
5
>Enter c:
6
Solutions to equation 1.0*x^2 + 5.0*x + 6.0 = 0 are -2.0 and -3.0
________________________________________
Example 2:
>Enter a:
0
>Enter b:
3
>Enter c:
6
Solution to equation 3.0*x + 6.0 = 0 is -2.0
________________________________________
Example 3:
>Enter a:
1
>Enter b:
2
>Enter c:
3
Solutions to equation 1.0*x^2 + 2.0*x + 3.0 = 0 are not real
________________________________________
Example 4:
>Enter a:
1
>Enter b:
2
>Enter c:
1
Solution to equation 1.0*x^2 + 2.0*x +1.0 = 0 is -1.0
Java Datastructure labs Question
Implement a menu based program with the following array-based list functions:
• ADD (at the end of array)
• INSERT (element at a given location)
• DELETE (element from a given location)
• SHOW (all array elements)
• COUNT (total number of elements)
• CLEAR (initialize array)
Implement a menu based program with the following array-based queue functions:
• ADD (an element to the end of queue)
• DELETE (an element from the front of queue)
• SHOW (all elements, starting at first, ending at last)
• COUNT (total number of elements)
• CLEAR (initialize queue)
Implement a program that will use a stack structure to check for correct placement of parentheses in an algebraic expression. Allow the use of ( ) [ ] { } characters as grouping symbols. Make sure that an error is reported for an expression of a form (...]
Implement a program that will use a stack structure to calculate the value of arithmetic postfix expressions. Assume that only one digit numbers will be used.
Example:
Input 12+3* should generate 9
Monday, September 7, 2009
Java DataStructure Programs
// ArrayIterator.java Authors: Lewis/Chase
//
// Represents an iterator over the elements of an array.
//********************************************************************
package jss2;
import java.util.*;
public class ArrayIterator
{
private int count; // the number of elements in the collection
private int current; // the current position in the iteration
private T[] items;
//-----------------------------------------------------------------
// Sets up this iterator using the specified items.
//-----------------------------------------------------------------
public ArrayIterator (T[] collection, int size)
{
items = collection;
count = size;
current = 0;
}
//-----------------------------------------------------------------
// Returns true if this iterator has at least one more element
// to deliver in the iteraion.
//-----------------------------------------------------------------
public boolean hasNext()
{
return (current < count);
}
//-----------------------------------------------------------------
// Returns the next element in the iteration. If there are no
// more elements in this itertion, a NoSuchElementException is
// thrown.
//-----------------------------------------------------------------
public T next()
{
if (! hasNext())
throw new NoSuchElementException();
current++;
return items[current - 1];
}
//-----------------------------------------------------------------
// The remove operation is not supported in this collection.
//-----------------------------------------------------------------
public void remove() throws UnsupportedOperationException
{
throw new UnsupportedOperationException();
}
}
------------------------------------------
//********************************************************************
// ArraySet.java Author: Lewis/Chase
//
// Represents an array implementation of a set.
//********************************************************************
package jss2;
import jss2.exceptions.*;
import java.util.*;
public class ArraySet
{
private static Random rand = new Random();
private final int DEFAULT_CAPACITY = 100;
private final int NOT_FOUND = -1;
private int count; // the current number of elements in the set
private T[] contents;
//-----------------------------------------------------------------
// Creates an empty set using the default capacity.
//-----------------------------------------------------------------
public ArraySet()
{
count = 0;
contents = (T[])(new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Creates an empty set using the specified capacity.
//-----------------------------------------------------------------
public ArraySet (int initialCapacity)
{
count = 0;
contents = (T[])(new Object[initialCapacity]);
}
//-----------------------------------------------------------------
// Adds the specified element to the set if it's not already
// present. Expands the capacity of the set array if necessary.
//-----------------------------------------------------------------
public void add (T element)
{
if (!(contains(element)))
{
if (size() == contents.length)
expandCapacity();
contents[count] = element;
count++;
}
}
//-----------------------------------------------------------------
// Adds the contents of the parameter to this set.
//-----------------------------------------------------------------
public void addAll (SetADT
{
Iterator
while (scan.hasNext())
add (scan.next());
}
//-----------------------------------------------------------------
// Removes a random element from the set and returns it. Throws
// an EmptySetException if the set is empty.
//-----------------------------------------------------------------
public T removeRandom() throws EmptySetException
{
if (isEmpty())
throw new EmptySetException();
int choice = rand.nextInt(count);
T result = contents[choice];
contents[choice] = contents[count-1]; // fill the gap
contents[count-1] = null;
count--;
return result;
}
//-----------------------------------------------------------------
// Removes the specified element from the set and returns it.
// Throws an EmptySetException if the set is empty and a
// NoSuchElementException if the target is not in the set.
//-----------------------------------------------------------------
public T remove (T target) throws EmptySetException,
NoSuchElementException
{
int search = NOT_FOUND;
if (isEmpty())
throw new EmptySetException();
for (int index=0; index < count && search == NOT_FOUND; index++)
if (contents[index].equals(target))
search = index;
if (search == NOT_FOUND)
throw new NoSuchElementException();
T result = contents[search];
contents[search] = contents[count-1];
contents[count-1] = null;
count--;
return result;
}
//-----------------------------------------------------------------
// Returns a new set that is the union of this set and the
// parameter.
//-----------------------------------------------------------------
public SetADT
{
ArraySet
for (int index = 0; index < count; index++)
both.add (contents[index]);
Iterator
while (scan.hasNext())
both.add (scan.next());
return both;
}
//-----------------------------------------------------------------
// Returns true if this set contains the specified target
// element.
//-----------------------------------------------------------------
public boolean contains (T target)
{
int search = NOT_FOUND;
for (int index=0; index < count && search == NOT_FOUND; index++)
if (contents[index].equals(target))
search = index;
return (search != NOT_FOUND);
}
//-----------------------------------------------------------------
// Returns true if this set contains exactly the same elements
// as the parameter.
//-----------------------------------------------------------------
public boolean equals (SetADT
{
boolean result = false;
ArraySet
ArraySet
T obj;
if (size() == set.size())
{
temp1.addAll(this);
temp2.addAll(set);
Iterator
while (scan.hasNext())
{
obj = scan.next();
if (temp1.contains(obj))
{
temp1.remove(obj);
temp2.remove(obj);
}
}
result = (temp1.isEmpty() && temp2.isEmpty());
}
return result;
}
//-----------------------------------------------------------------
// Returns true if this set is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty()
{
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this set.
//-----------------------------------------------------------------
public int size()
{
return count;
}
//-----------------------------------------------------------------
// Returns an iterator for the elements currently in this set.
//-----------------------------------------------------------------
public Iterator
{
return new ArrayIterator
}
//-----------------------------------------------------------------
// Returns a string representation of this set.
//-----------------------------------------------------------------
public String toString()
{
String result = "";
for (int index=0; index < count; index++)
result = result + contents[index].toString() + "\n";
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the set with
// twice the capacity of the old one.
//-----------------------------------------------------------------
private void expandCapacity()
{
T[] larger = (T[])(new Object[contents.length*2]);
for (int index=0; index < contents.length; index++)
larger[index] = contents[index];
contents = larger;
}
}
--------------------------------------------------
//********************************************************************
// ElementNotFoundException.java Authors: Lewis/Chase
//
// Represents the situation in which a target element is not
// present in a collection
//********************************************************************
package jss2.exceptions;
public class ElementNotFoundException extends RuntimeException
{
//-----------------------------------------------------------------
// Sets up this exception with an appropriate message.
//-----------------------------------------------------------------
public ElementNotFoundException (String collection)
{
super ("The target element is not in this " + collection);
}
}
-----------------------------------------------------
//********************************************************************
// EmptySetException.java Authors: Lewis/Chase
//
// Represents the situation in which a set is empty.
//********************************************************************
package jss2.exceptions;
public class EmptySetException extends RuntimeException
{
//-----------------------------------------------------------------
// Creates the exception.
//-----------------------------------------------------------------
public EmptySetException()
{
super ("The set is empty.");
}
//-----------------------------------------------------------------
// Creates the exceptio with the specified message.
//-----------------------------------------------------------------
public EmptySetException (String message)
{
super (message);
}
}
-----------------------------------------------------
package trysets;
import jss2.*;
import java.util.*;
public class IntegerSetTester {
public static void main(String[] args) {
System.out.println("Lab 2: Part I written by YOURNAME");
System.out.println("Creating set1--------------------");
SetADT
}
}
------------------------------------------------
//********************************************************************
// SetADT.java Authors: Lewis/Chase
//
// Defines the interface to a set collection.
//********************************************************************
package jss2;
import java.util.Iterator;
public interface SetADT
{
// Adds one element to this set, ignoring duplicates
public void add (T element);
// Removes and returns a random element from this set
public T removeRandom ();
// Removes and returns the specified element from this set
public T remove (T element);
// Returns the union of this set and the parameter
public SetADT
// Returns true if this set contains the parameter
public boolean contains (T target);
// Returns true if this set and the parameter contain exactly
// the same elements
public boolean equals (SetADT
// Returns true if this set contains no elements
public boolean isEmpty();
// Returns the number of elements in this set
public int size();
// Returns an iterator for the elements in this set
public Iterator
// Returns a string representation of this set
public String toString();
}
--------------------------------------------
package trysets;
import java.io.*;
import java.util.*;
/**
*
Title:
WordReader*
Description:
Provides an "iterator" over the file filename* to return individual words, while removing leading and trailing
* punctuation. WordReader throws an IOException if it is unable
* to open the file corresponding to filename. However, for other
* errors, it reports errors by returning null for the next word.
*/
public class WordReader implements Iterator
private static final String punctuation = ".,:)({}[]';)-=+!@`";
private BufferedReader read;
private String name;
private String nextWord;
private boolean more;
private StringTokenizer tokens;
public WordReader(String filename) throws IOException {
name = filename;
more = true;
read = new BufferedReader(new FileReader(filename));
tokens = null;
updateWord();
}
public boolean hasNext() {
return more;
}
public String next() {
if (!more)
throw new NoSuchElementException("No more words in " + name);
String thisWord = nextWord;
updateWord();
return thisWord;
}
public void remove() {
throw new UnsupportedOperationException(
"Can not remove elements from file");
}
private String trimPunctuation(String word) {
int start = 0;
// find first non-punctuation
int end = word.length();
while (start < end && punctuation.indexOf(word.charAt(start)) != -1) {
start++;
}
if (start >= end) { // all punctuation
return null;
} while (punctuation.indexOf(word.charAt(end - 1)) != -1) {
end--;
}
return word.substring(start, end);
}
private void updateWord() {
try {
while (more) {
if (tokens == null) {
String thisLine = read.readLine();
if (thisLine == null) {
throw new IOException("Empty line");
}
tokens = new StringTokenizer(thisLine);
}
if (tokens.hasMoreTokens()) {
nextWord = trimPunctuation(tokens.nextToken());
if (nextWord != null) {
return;
}
} else {
tokens = null;
}
}
} catch (Exception e) {
more = false;
nextWord = null;
try {
read.close();
} catch (Exception e1) {}
}
}
}
Sunday, September 6, 2009
Sets of Integer and Words
• Become familiar with the SetADT interface
• Learn to use iterators
• Learn to use generic types
• Read files using provided libraries
• Practice incremental development
Hand-in Requirements
• Source for IntegerSetTester.java (10 pts)
• Source for WordSetTester.java (10 pts)
All projects and laboratories will be submitted electronically through webCT. Zip up your entire project directory to submit as the source. (Right click on the project folder and follow the SentTo link.)
Overview:
This project provides practice with using generics, iterators, and the SetADT. You will create two test programs. IntegerSetTester will create sets of integers and perform various set operations on them. WortSetTester will create sets of words from a file and output statistics.
Part I: Sets of integers
• Download the trysetsproject.zip file and import it into your Eclipse workspace as a starting point for this project. Use File -> Import > General -> Existing Projects into Workspace -> Select Archive File to import the zip file, see the "Bringing your program home" section in http://www.cs.utsa.edu/~javalab/lab/eclipse/getstartedeclipse.html for more details on how to import the zipped project.
• Compile and run IntegerSetTester.
• Create a new SetADT called set1 of Integer objects. Use ArraySet as the implementation.
• Add 1000 random Integer objects (with values between 1 and 50) to set1.
• Output set1 and its size. Why doesn't set1 contain 1000 elements?
• Create an Integer iterator for set1. Remove from set1 the first item returned by the iterator.
• Create a second set called set2 by adding 100 random Integer objects with values between 1 and 10.
• Output set2.
• Create a set3 which is the union of set1 and set2. Output set3 and its size.
• (On your own) Create a set4 which is the intersection of set1 and set2. Output set4 and its size.
• (On your own) Find and output the maximum value in set1.
Part II: Reading words from a file using WordReader
The WordReader class provides a String iterator over the words of a file.
• Create a new class called WordSetTester in the trysets project.
• Add code to WordSetTester to create a WordReader for short.txt.
• Write a loop that outputs the successive words obtained from WordReader one per line.
Part III: Creating sets of words from a file
The code in this part should be added to the WordSetTester class of Part III.
• Create a SetADT called shortSet that contains String objects.
• Create a WordReader called shortReader for the file short.txt.
• Add the words in short.txt to shortSet (by iterating through shortReader).
• Output the unique words and the number of unique words in short.txt (by using shortSet).
• (On your own) Create a set called poeSet that contains the words in the file poe.txt. Output the number of unique words in poe.txt.
• (On your own) Output the words that are in both shortSet and poeSet.
• (On your own) Output the words that are in shortSet but not in poeSet.
Simple class hierarchy based on the Currency class
• Become familiar with the rules and facilities.
• Log in to your Windows and Unix accounts.
• Set up your Windows and Unix accounts so that the passwords agree.
• Use a Java development environment
• Create and run a simple Java program using simple classes.
Hand-in Requirements:
• Source code for Currency.java, Quarter.java, Dime.java, Nickel.java and Penny.java (10 pts)
• Source code for CurrencyTester.java (10 pts)
All projects and laboratories have to be Eclipse projects that will be submitted electronically through webCT under the Submissions menu. Zip up your entire project directory to submit as the source. (Right click on the project folder and follow the Send To link.)
Overview:
The goal of this laboratory is for you to get your account set up and to understand how to run simple Java programs. See http://www.cs.utsa.edu/~javalab/lab/accountLogin.html for information on how to set up your account. It is important that you get all account problems resolved in the first week of class. You will have an account on the CS network that works on the Windows, Sun and Linux (Unix) machines in the Computer Science Laboratories. We will mainly be using Windows machines for this course. You will need to log in to both your Windows and Unix accounts to change your passwords if you are new to the system. You can also go to SB 3.02.02 during open laboratory hours ( http://www.cs.utsa.edu/~javalab/lab/schedule.html) and reset your passwords. If you are unfamiliar with the system, please ask a tutor to help. The tutors are available to give you as much help as you need on the laboratories. Please ask for help if you are having trouble.
Part I: Running a simple project
Refer to http://www.cs.utsa.edu/~javalab/lab/eclipse/getstartedeclipse.html for an introduction on how to get started with Eclipse.
When you start Eclipse it will ask you to select a workspace. This is the directory in which all your Eclipse projects will be located. (Theoretically you can switch between different workspaces, but for now let's assume you only have one workspace.) We recommend that you use a directory such as Z:\working\cs2123 as your workspace directory. This laboratory is based on the Currency class. The Currency class has a value, a name, and a two-letter country code. You can find out the name, the value, and the country code. You can also find out whether or not a Currency object is equal to another object. Currency are equal if they are currency with the same name, value, and a country code. (US is the country code for the United States.) All of our classes will also have a toString method for debugging.
Create a new project called currencyproject.
• Open Eclipse and select your workspace directory (such as Z:\working\cs2123\recitations).
• Create a new Eclipse project by selecting File -> New -> Java Project. Give the Name as currencyproject (all lower case). Press Finish.
• Create a Currency class by selecting File -> New -> Class. Use Currency as the Class name and type in currency as the package name. Pay attention to upper and lower case when you type, as Java is case-sensitive. Eclipse will create an empty class called Currency. Implement the functionality of Currency.
• Create a CurrencyTester class which has a main method. (You can select a checkbox that does that for you during the class creation process.)
• Make sure that the main method of CurrencyTester begins with a statement to output the message "This program was written by ... ".
• Add code to CurrencyTester to create a Currency object and to test the methods to get the name and value.
• Create 2 objects of type Currency with different values, but the same names. Output their values using toString. Test to see whether they are equal.
• Also test two different currency objects for equality.
• Create Currency objects with 0 and negative values.
• Create a Quarter class that extends Currency and is specialized to represent quarters. Quarters are US currency. Note: If you have the Currency class (not Currency.java) selected in Eclipse's package explorer and then add a new class, then currency.Currency is automatically selected as the super class. Write test code for Quarter. Subclasses of Currency represent specific denomiations. They should have two constructors: one which is the same as the superclass and one which has no parameters.
Part II: On your own
• Add the following code to CurrencyTester. In a loop which is repeated 10 times, create a new Currency object and assign it to the variable myCurrency. Create each currency object with name theCurrency and value which is a random int value between 1 and 100. Use US as the country code. (Use the Random class with the nextInt method.) Print out each currency object as it is created. After the loop print the maximum currency value, the minimum currency value and the average currency value. Do not use an array.
• Add the Dime, Nickel and Penny classes to the currencyproject. Add test code to CurrencyTester to create and compare various currency.