SlideShare a Scribd company logo
Soundreader/.classpath
Soundreader/.project
Soundreader
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
Soundreader/.settings/org.eclipse.jdt.core.prefs
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enable
d
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
Soundreader/bin/ArrayStack.classpublicsynchronizedclass
ArrayStack {
private Object[] data;
private int size;
public void ArrayStack();
public boolean isEmpty();
protected boolean isFull();
public Object peek();
public Object pop();
public void push(Object);
protected void stretch();
}
Soundreader/bin/DStack.classpublicabstractinterface DStack {
publicabstract boolean isEmpty();
publicabstract void push(double);
publicabstract double pop();
publicabstract double peek();
}
Soundreader/bin/gtd/stack/ListStackNode.classpackage
gtd.stack;
publicfinalsynchronizedclass ListStackNode {
privatestaticfinal EpsilonStackNode EMPTY;
privatefinal String nodeName;
privatefinal AbstractStackNode[] children;
privatefinal AbstractStackNode emptyChild;
public void ListStackNode(int, int, AbstractStackNode,
String, boolean);
private void ListStackNode(ListStackNode, int);
AbstractStackNode[] generateChildren(AbstractStackNode);
private AbstractStackNode generateEmptyChild();
public String getName();
public AbstractStackNode getCleanCopy(int);
public AbstractStackNode[] getChildren();
public boolean canBeEmpty();
public AbstractStackNode getEmptyChild();
public String toString();
}
Soundreader/bin/ListStack.classpublicsynchronizedclass
ListStack {
private ListNode topOfStack;
public void ListStack();
public boolean isEmpty();
public void makeEmpty();
public void push(Object);
public void pop();
public Object top();
public Object topAndPop();
}
Soundreader/bin/Reverse.classpublicsynchronizedclass Reverse
{
public void Reverse();
publicstatic void main(String[]);
}
Soundreader/Screenshot (14).png
Soundreader/Screenshot (15).png
Soundreader/Screenshot (16).png
Soundreader/src/ArrayStack.javaSoundreader/src/ArrayStack.ja
vaimport java.util.EmptyStackException;
publicclassArrayStack<E>implementsDStack<E>{
/** Array of items in this Stack. */
private E[] data;
/** Number of items currently in this Stack. */
privateint size;
/** The Stack is initally empty. */
publicArrayStack(){
data =(E[])(newObject[1]);// This causes a compiler warni
ng
size =0;
}
publicboolean isEmpty(){
return size ==0;
}
/** Return true if data is full. */
protectedboolean isFull(){
return size == data.length;
}
public E peek(){
if(isEmpty()){
thrownewEmptyStackException();
}
return data[size -1];
}
public E pop(){
if(isEmpty()){
thrownewEmptyStackException();
}
size--;
return data[size];
}
publicvoid push(E target){
if(isFull()){
stretch();
}
data[size]= target;
size++;
}
/** Double the length of data. */
protectedvoid stretch(){
E[] newData =(E[])(newObject[data.length *2]);// Warning
for(int i =0; i < data.length; i++){
newData[i]= data[i];
}
data = newData;
}
}
}
Soundreader/src/DStack.javaSoundreader/src/DStack.java/**
* Interface for a stack of primitive doubles.
* @version
*
* NOTE: The comments for this interface are horrible! You wil
l
* need to write something better for your implementations.
*/
publicinterfaceDStack{
/**
* is empty?
*/
publicboolean isEmpty();
/**
* push
*/
publicvoid push(double d);
/**
* pop
* @return the deleted value
* @throws EmptyStackException if stack is empty
*/
publicdouble pop();
/**
* peek
* @throws EmptyStackException if stack is empty
*/
publicdouble peek();
}
Soundreader/src/gtd/stack/ListStackNode.javaSoundreader/src/g
td/stack/ListStackNode.javapackage gtd.stack;
publicfinalclassListStackNodeextendsAbstractExpandableStack
Node{
privatefinalstaticEpsilonStackNode EMPTY =newEpsilonStack
Node(DEFAULT_LIST_EPSILON_ID,0);
privatefinalString nodeName;
privatefinalAbstractStackNode[] children;
privatefinalAbstractStackNode emptyChild;
publicListStackNode(int id,int dot,AbstractStackNode child,Stri
ng nodeName,boolean isPlusList){
super(id, dot);
this.nodeName = nodeName;
this.children = generateChildren(child);
this.emptyChild = isPlusList ?null: generateEmptyChild();
}
privateListStackNode(ListStackNode original,int startLocation)
{
super(original, startLocation);
nodeName = original.nodeName;
children = original.children;
emptyChild = original.emptyChild;
}
privateAbstractStackNode[] generateChildren(AbstractStackNod
e child){
AbstractStackNode listNode = child.getCleanCopy(DEFAULT_
START_LOCATION);
listNode.markAsEndNode();
listNode.setProduction(newAbstractStackNode[]{listNode,
listNode});
returnnewAbstractStackNode[]{listNode};
}
privateAbstractStackNode generateEmptyChild(){
AbstractStackNode empty = EMPTY.getCleanCopy(DEFAULT_
START_LOCATION);
empty.setProduction(newAbstractStackNode[]{empty});
empty.markAsEndNode();
return empty;
}
publicString getName(){
return nodeName;
}
publicAbstractStackNode getCleanCopy(int startLocation){
returnnewListStackNode(this, startLocation);
}
publicAbstractStackNode[] getChildren(){
return children;
}
publicboolean canBeEmpty(){
return(emptyChild !=null);
}
publicAbstractStackNode getEmptyChild(){
return emptyChild;
}
publicString toString(){
StringBuilder sb =newStringBuilder();
sb.append(nodeName);
sb.append(getId());
sb.append('(');
sb.append(startLocation);
sb.append(')');
return sb.toString();
}
}
Soundreader/src/ListStack.javaSoundreader/src/ListStack.java//
ListStack class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*************
********
// void push( x ) --> Insert x
// void pop( ) --> Remove most recently inserted item
// AnyType top( ) --> Return most recently inserted item
// AnyType topAndPop( ) --
> Return and remove most recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS*************************
*******
// top, pop, or topAndPop on empty stack
publicclassListStack<AnyType>implementsDStack<AnyType>
{
/**
* Construct the stack.
*/
publicListStack()
{
topOfStack =null;
}
/**
* Test if the stack is logically empty.
* @return true if empty, false otherwise.
*/
publicboolean isEmpty()
{
return topOfStack ==null;
}
/**
* Make the stack logically empty.
*/
publicvoid makeEmpty()
{
topOfStack =null;
}
/**
* Insert a new item into the stack.
* @param x the item to insert.
*/
publicvoid push(AnyType x )
{
topOfStack =newListNode<AnyType>( x, topOfStack );
}
/**
* Remove the most recently inserted item from the stack.
* @throws UnderflowException if the stack is empty.
*/
publicvoid pop()
{
if( isEmpty())
thrownewUnderflowException("ListStack pop");
topOfStack = topOfStack.next;
}
/**
* Get the most recently inserted item in the stack.
* Does not alter the stack.
* @return the most recently inserted item in the stack.
* @throws UnderflowException if the stack is empty.
*/
publicAnyType top()
{
if( isEmpty())
thrownewUnderflowException("ListStack top");
return topOfStack.element;
}
/**
* Return and remove the most recently inserted item
* from the stack.
* @return the most recently inserted item in the stack.
* @throws UnderflowException if the stack is empty.
*/
publicAnyType topAndPop()
{
if( isEmpty())
thrownewUnderflowException("ListStack topAndPop");
AnyType topItem = topOfStack.element;
topOfStack = topOfStack.next;
return topItem;
}
privateListNode<AnyType> topOfStack;
}
Soundreader/src/Reverse.javaSoundreader/src/Reverse.javaimpo
rt java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Read a .dat file and reverse it.
* @version
*/
publicclassReverse{
publicstaticvoid main(String[]args){
if(args.length !=3){
System.err.println(" Incorrect number of arguments");
System.err.println(" Usage: ");
System.err.
println("tjava Reverse <stack type> <input file> <outp
ut file>");
System.exit(1);
}
boolean useList =true;
if(args[0].compareTo("list")==0)
useList =true;
elseif(args[0].compareTo("array")==0)
useList =false;
else{
System.err.println("tSaw "+args[0]+" instead of list or array as
first argument");
System.exit(1);
}
try{
//
// Set up the input file to read, and the output file to write to
//
BufferedReader fileIn =
newBufferedReader(newFileReader(args[1]));
PrintWriter fileOut =
newPrintWriter(new
BufferedWriter(newFileWriter(args[2])));
//
// Read the first line of the .dat file to get sample rate.
// We want to store the sample rate value in a variable,
// but we can ignore the "; Sample Rate" part of the line.
// Step through the first line one token (word) at a time
// using the StringTokenizer. The fourth token is the one
// we want (the sample rate).
//
StringTokenizer str;
String oneLine;
int sampleRate;
String strJunk;
oneLine = fileIn.readLine();
str =newStringTokenizer(oneLine);
strJunk = str.nextToken();// Read in semicolon
strJunk = str.nextToken();// Read in "Sample"
strJunk = str.nextToken();// Read in "Rate"
// Read in sample rate
sampleRate =Integer.parseInt(str.nextToken());
//
// Read in the remainder of the file on line at a time.
// The values in the first column are thrown away.
// Place values from the second column on the stack.
// Stop reading if we reach the end of the file.
//
DStack s;
if(useList)
s =newListStack();
else
s =newArrayStack();
String timestep;
double data;
int count =0;
while((oneLine = fileIn.readLine())!=null){
if(oneLine.charAt(0)==';'){
continue;
}
str =newStringTokenizer(oneLine);
// Read in time step value from first column
timestep = str.nextToken();
// Read in data value from second column
data =Double.parseDouble(str.nextToken());
s.push(data);
count++;
}
System.out.println(count+" samples in file");
//
// Print the data values to output .dat file.
// First, output the header line:
// "; Sample Rate <sample rate>"
//
fileOut.println("; Sample Rate "+ sampleRate);
// Since the first column consists of numbers which start
// at 0 and increase by 1/sampleRate every time slice, we'll
// just use numSteps to recalculate these numbers.
int numSteps =0;
// Finally, we print the values in reverse order (by popping
// them off the stack). The first column consists of numbers
// which start at 0 and increase by 1/sampleRate per row, so
// we'll use numSteps/sampleRate to recalculate the appropriate
// values. Print a tab for uniform spacing.
while(!s.isEmpty()){
fileOut.println((double) numSteps / sampleRate +"t"
+
s.pop());
numSteps++;
}
//
// Close the files
//
fileIn.close();
fileOut.close();
}catch(IOException ioe){
System.err.
println
("Error opening/reading/writing input or output file.");
System.exit(1);
}catch(NumberFormatException nfe){
System.err.println(nfe.toString());
System.err.println("Error in file format");
System.exit(1);
}
}
}

More Related Content

ODP
Ast transformations
PDF
Java Programming Must implement a storage manager that main.pdf
DOCX
Advance Java Programs skeleton
PPT
JSConf: All You Can Leet
DOCX
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
PDF
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
PPTX
Ian 20150116 java script oop
ODP
AST Transformations at JFokus
Ast transformations
Java Programming Must implement a storage manager that main.pdf
Advance Java Programs skeleton
JSConf: All You Can Leet
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Ian 20150116 java script oop
AST Transformations at JFokus

Similar to Soundreader.classpathSoundreader.project Soundre.docx (20)

PPT
Web Optimization Summit: Coding for Performance
PDF
Unittests für Dummies
PPTX
A topology of memory leaks on the JVM
PPTX
Androidaop 170105090257
DOCX
My java file
PDF
JavaScript for PHP developers
PDF
Swift Programming Language
PDF
GoCracow #5 Bartlomiej klimczak - GoBDD
DOC
Jsphp 110312161301-phpapp02
PPTX
05 pig user defined functions (udfs)
PPT
Javascript quiz. Questions to ask when recruiting developers.
DOCX
Assignment #2.classpathAssignment #2.project Assig.docx
PDF
JavaScript and UI Architecture Best Practices
ODP
Groovy Ast Transformations (greach)
PDF
G* on GAE/J 挑戦編
PDF
アプリを弄ってみる #1 #antama_ws
ODP
AST Transformations
PPTX
CodeCamp Iasi 10 march 2012 - Practical Groovy
DOCX
Exercícios Netbeans - Vera Cymbron
PPTX
Java and SPARQL
Web Optimization Summit: Coding for Performance
Unittests für Dummies
A topology of memory leaks on the JVM
Androidaop 170105090257
My java file
JavaScript for PHP developers
Swift Programming Language
GoCracow #5 Bartlomiej klimczak - GoBDD
Jsphp 110312161301-phpapp02
05 pig user defined functions (udfs)
Javascript quiz. Questions to ask when recruiting developers.
Assignment #2.classpathAssignment #2.project Assig.docx
JavaScript and UI Architecture Best Practices
Groovy Ast Transformations (greach)
G* on GAE/J 挑戦編
アプリを弄ってみる #1 #antama_ws
AST Transformations
CodeCamp Iasi 10 march 2012 - Practical Groovy
Exercícios Netbeans - Vera Cymbron
Java and SPARQL
Ad

More from whitneyleman54422 (20)

DOCX
In this unit, you will experience the powerful impact communication .docx
DOCX
In this task, you will write an analysis (suggested length of 3–5 .docx
DOCX
In this SLP you will identify where the major transportation modes a.docx
DOCX
In this module the student will present writing which focuses attent.docx
DOCX
In this module, we looked at a variety of styles in the Renaissa.docx
DOCX
In this experiential learning experience, you will evaluate a health.docx
DOCX
In this essay you should combine your practice responding and analyz.docx
DOCX
In this Discussion, pick one film to write about and answer ques.docx
DOCX
In this assignment, you will identify and interview a family who.docx
DOCX
In this assignment, you will assess the impact of health legisla.docx
DOCX
In this assignment, you will create a presentation. Select a topic o.docx
DOCX
In this assignment, the student will understand the growth and devel.docx
DOCX
In this assignment, I want you to locate two pieces of news detailin.docx
DOCX
In this assignment worth 150 points, you will consider the present-d.docx
DOCX
In the readings thus far, the text identified many early American in.docx
DOCX
In the Roman Colony, leaders, or members of the court, were to be.docx
DOCX
In the provided scenario there are a few different crimes being .docx
DOCX
Stoichiometry Lab – The Chemistry Behind Carbonates reacting with .docx
DOCX
Stock-Trak Portfolio Report Write-Up GuidelinesYou may want to.docx
DOCX
Stewart Guthrie, Faces in the Clouds Oxford UP, 1993.docx
In this unit, you will experience the powerful impact communication .docx
In this task, you will write an analysis (suggested length of 3–5 .docx
In this SLP you will identify where the major transportation modes a.docx
In this module the student will present writing which focuses attent.docx
In this module, we looked at a variety of styles in the Renaissa.docx
In this experiential learning experience, you will evaluate a health.docx
In this essay you should combine your practice responding and analyz.docx
In this Discussion, pick one film to write about and answer ques.docx
In this assignment, you will identify and interview a family who.docx
In this assignment, you will assess the impact of health legisla.docx
In this assignment, you will create a presentation. Select a topic o.docx
In this assignment, the student will understand the growth and devel.docx
In this assignment, I want you to locate two pieces of news detailin.docx
In this assignment worth 150 points, you will consider the present-d.docx
In the readings thus far, the text identified many early American in.docx
In the Roman Colony, leaders, or members of the court, were to be.docx
In the provided scenario there are a few different crimes being .docx
Stoichiometry Lab – The Chemistry Behind Carbonates reacting with .docx
Stock-Trak Portfolio Report Write-Up GuidelinesYou may want to.docx
Stewart Guthrie, Faces in the Clouds Oxford UP, 1993.docx
Ad

Recently uploaded (20)

PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Trump Administration's workforce development strategy
PPTX
Cell Types and Its function , kingdom of life
PDF
Updated Idioms and Phrasal Verbs in English subject
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
01-Introduction-to-Information-Management.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
RMMM.pdf make it easy to upload and study
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
Trump Administration's workforce development strategy
Cell Types and Its function , kingdom of life
Updated Idioms and Phrasal Verbs in English subject
History, Philosophy and sociology of education (1).pptx
01-Introduction-to-Information-Management.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
A systematic review of self-coping strategies used by university students to ...
RMMM.pdf make it easy to upload and study
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Computing-Curriculum for Schools in Ghana
Practical Manual AGRO-233 Principles and Practices of Natural Farming
What if we spent less time fighting change, and more time building what’s rig...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Chapter 2 Heredity, Prenatal Development, and Birth.pdf

Soundreader.classpathSoundreader.project Soundre.docx

  • 2. org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.source=1.8 Soundreader/bin/ArrayStack.classpublicsynchronizedclass ArrayStack { private Object[] data; private int size; public void ArrayStack(); public boolean isEmpty(); protected boolean isFull(); public Object peek(); public Object pop(); public void push(Object); protected void stretch(); } Soundreader/bin/DStack.classpublicabstractinterface DStack { publicabstract boolean isEmpty(); publicabstract void push(double); publicabstract double pop(); publicabstract double peek(); }
  • 3. Soundreader/bin/gtd/stack/ListStackNode.classpackage gtd.stack; publicfinalsynchronizedclass ListStackNode { privatestaticfinal EpsilonStackNode EMPTY; privatefinal String nodeName; privatefinal AbstractStackNode[] children; privatefinal AbstractStackNode emptyChild; public void ListStackNode(int, int, AbstractStackNode, String, boolean); private void ListStackNode(ListStackNode, int); AbstractStackNode[] generateChildren(AbstractStackNode); private AbstractStackNode generateEmptyChild(); public String getName(); public AbstractStackNode getCleanCopy(int); public AbstractStackNode[] getChildren(); public boolean canBeEmpty(); public AbstractStackNode getEmptyChild(); public String toString(); } Soundreader/bin/ListStack.classpublicsynchronizedclass ListStack { private ListNode topOfStack; public void ListStack(); public boolean isEmpty(); public void makeEmpty(); public void push(Object); public void pop(); public Object top(); public Object topAndPop(); } Soundreader/bin/Reverse.classpublicsynchronizedclass Reverse
  • 4. { public void Reverse(); publicstatic void main(String[]); } Soundreader/Screenshot (14).png Soundreader/Screenshot (15).png Soundreader/Screenshot (16).png Soundreader/src/ArrayStack.javaSoundreader/src/ArrayStack.ja vaimport java.util.EmptyStackException; publicclassArrayStack<E>implementsDStack<E>{ /** Array of items in this Stack. */ private E[] data; /** Number of items currently in this Stack. */ privateint size; /** The Stack is initally empty. */ publicArrayStack(){ data =(E[])(newObject[1]);// This causes a compiler warni ng size =0; } publicboolean isEmpty(){ return size ==0; } /** Return true if data is full. */ protectedboolean isFull(){
  • 5. return size == data.length; } public E peek(){ if(isEmpty()){ thrownewEmptyStackException(); } return data[size -1]; } public E pop(){ if(isEmpty()){ thrownewEmptyStackException(); } size--; return data[size]; } publicvoid push(E target){ if(isFull()){ stretch(); } data[size]= target; size++; } /** Double the length of data. */ protectedvoid stretch(){ E[] newData =(E[])(newObject[data.length *2]);// Warning for(int i =0; i < data.length; i++){ newData[i]= data[i]; } data = newData; }
  • 6. } } Soundreader/src/DStack.javaSoundreader/src/DStack.java/** * Interface for a stack of primitive doubles. * @version * * NOTE: The comments for this interface are horrible! You wil l * need to write something better for your implementations. */ publicinterfaceDStack{ /** * is empty? */ publicboolean isEmpty(); /** * push */ publicvoid push(double d); /** * pop * @return the deleted value * @throws EmptyStackException if stack is empty */ publicdouble pop(); /** * peek * @throws EmptyStackException if stack is empty */ publicdouble peek(); }
  • 7. Soundreader/src/gtd/stack/ListStackNode.javaSoundreader/src/g td/stack/ListStackNode.javapackage gtd.stack; publicfinalclassListStackNodeextendsAbstractExpandableStack Node{ privatefinalstaticEpsilonStackNode EMPTY =newEpsilonStack Node(DEFAULT_LIST_EPSILON_ID,0); privatefinalString nodeName; privatefinalAbstractStackNode[] children; privatefinalAbstractStackNode emptyChild; publicListStackNode(int id,int dot,AbstractStackNode child,Stri ng nodeName,boolean isPlusList){ super(id, dot); this.nodeName = nodeName; this.children = generateChildren(child); this.emptyChild = isPlusList ?null: generateEmptyChild(); } privateListStackNode(ListStackNode original,int startLocation) { super(original, startLocation); nodeName = original.nodeName; children = original.children; emptyChild = original.emptyChild; }
  • 8. privateAbstractStackNode[] generateChildren(AbstractStackNod e child){ AbstractStackNode listNode = child.getCleanCopy(DEFAULT_ START_LOCATION); listNode.markAsEndNode(); listNode.setProduction(newAbstractStackNode[]{listNode, listNode}); returnnewAbstractStackNode[]{listNode}; } privateAbstractStackNode generateEmptyChild(){ AbstractStackNode empty = EMPTY.getCleanCopy(DEFAULT_ START_LOCATION); empty.setProduction(newAbstractStackNode[]{empty}); empty.markAsEndNode(); return empty; } publicString getName(){ return nodeName; } publicAbstractStackNode getCleanCopy(int startLocation){ returnnewListStackNode(this, startLocation); } publicAbstractStackNode[] getChildren(){ return children; } publicboolean canBeEmpty(){ return(emptyChild !=null); }
  • 9. publicAbstractStackNode getEmptyChild(){ return emptyChild; } publicString toString(){ StringBuilder sb =newStringBuilder(); sb.append(nodeName); sb.append(getId()); sb.append('('); sb.append(startLocation); sb.append(')'); return sb.toString(); } } Soundreader/src/ListStack.javaSoundreader/src/ListStack.java// ListStack class // // CONSTRUCTION: with no initializer // // ******************PUBLIC OPERATIONS************* ******** // void push( x ) --> Insert x // void pop( ) --> Remove most recently inserted item // AnyType top( ) --> Return most recently inserted item // AnyType topAndPop( ) -- > Return and remove most recent item // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // ******************ERRORS************************* ******* // top, pop, or topAndPop on empty stack
  • 10. publicclassListStack<AnyType>implementsDStack<AnyType> { /** * Construct the stack. */ publicListStack() { topOfStack =null; } /** * Test if the stack is logically empty. * @return true if empty, false otherwise. */ publicboolean isEmpty() { return topOfStack ==null; } /** * Make the stack logically empty. */ publicvoid makeEmpty() { topOfStack =null; } /** * Insert a new item into the stack. * @param x the item to insert. */ publicvoid push(AnyType x ) { topOfStack =newListNode<AnyType>( x, topOfStack ); }
  • 11. /** * Remove the most recently inserted item from the stack. * @throws UnderflowException if the stack is empty. */ publicvoid pop() { if( isEmpty()) thrownewUnderflowException("ListStack pop"); topOfStack = topOfStack.next; } /** * Get the most recently inserted item in the stack. * Does not alter the stack. * @return the most recently inserted item in the stack. * @throws UnderflowException if the stack is empty. */ publicAnyType top() { if( isEmpty()) thrownewUnderflowException("ListStack top"); return topOfStack.element; } /** * Return and remove the most recently inserted item * from the stack. * @return the most recently inserted item in the stack. * @throws UnderflowException if the stack is empty. */ publicAnyType topAndPop() { if( isEmpty()) thrownewUnderflowException("ListStack topAndPop"); AnyType topItem = topOfStack.element;
  • 12. topOfStack = topOfStack.next; return topItem; } privateListNode<AnyType> topOfStack; } Soundreader/src/Reverse.javaSoundreader/src/Reverse.javaimpo rt java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Read a .dat file and reverse it. * @version */ publicclassReverse{ publicstaticvoid main(String[]args){ if(args.length !=3){ System.err.println(" Incorrect number of arguments"); System.err.println(" Usage: "); System.err. println("tjava Reverse <stack type> <input file> <outp ut file>"); System.exit(1); } boolean useList =true; if(args[0].compareTo("list")==0) useList =true;
  • 13. elseif(args[0].compareTo("array")==0) useList =false; else{ System.err.println("tSaw "+args[0]+" instead of list or array as first argument"); System.exit(1); } try{ // // Set up the input file to read, and the output file to write to // BufferedReader fileIn = newBufferedReader(newFileReader(args[1])); PrintWriter fileOut = newPrintWriter(new BufferedWriter(newFileWriter(args[2]))); // // Read the first line of the .dat file to get sample rate. // We want to store the sample rate value in a variable, // but we can ignore the "; Sample Rate" part of the line. // Step through the first line one token (word) at a time // using the StringTokenizer. The fourth token is the one // we want (the sample rate). // StringTokenizer str; String oneLine; int sampleRate; String strJunk; oneLine = fileIn.readLine(); str =newStringTokenizer(oneLine); strJunk = str.nextToken();// Read in semicolon strJunk = str.nextToken();// Read in "Sample"
  • 14. strJunk = str.nextToken();// Read in "Rate" // Read in sample rate sampleRate =Integer.parseInt(str.nextToken()); // // Read in the remainder of the file on line at a time. // The values in the first column are thrown away. // Place values from the second column on the stack. // Stop reading if we reach the end of the file. // DStack s; if(useList) s =newListStack(); else s =newArrayStack(); String timestep; double data; int count =0; while((oneLine = fileIn.readLine())!=null){ if(oneLine.charAt(0)==';'){ continue; } str =newStringTokenizer(oneLine); // Read in time step value from first column timestep = str.nextToken(); // Read in data value from second column data =Double.parseDouble(str.nextToken()); s.push(data); count++; } System.out.println(count+" samples in file");
  • 15. // // Print the data values to output .dat file. // First, output the header line: // "; Sample Rate <sample rate>" // fileOut.println("; Sample Rate "+ sampleRate); // Since the first column consists of numbers which start // at 0 and increase by 1/sampleRate every time slice, we'll // just use numSteps to recalculate these numbers. int numSteps =0; // Finally, we print the values in reverse order (by popping // them off the stack). The first column consists of numbers // which start at 0 and increase by 1/sampleRate per row, so // we'll use numSteps/sampleRate to recalculate the appropriate // values. Print a tab for uniform spacing. while(!s.isEmpty()){ fileOut.println((double) numSteps / sampleRate +"t" + s.pop()); numSteps++; } // // Close the files // fileIn.close(); fileOut.close(); }catch(IOException ioe){ System.err. println
  • 16. ("Error opening/reading/writing input or output file."); System.exit(1); }catch(NumberFormatException nfe){ System.err.println(nfe.toString()); System.err.println("Error in file format"); System.exit(1); } } }