In your lab05, replace instructor's Tokenizer class and MyStackQueue packag

Objective:
The objective of this lab is to get you some experience in processing strings character by
character and in implementing stacks and queues in a class package.
The programming assignment:
In your lab05, replace instructor’s Tokenizer class and MyStackQueue package with your own.
Requirements:
1. You must use an array to implement your queue.
2. You must use a linked list to implement your stack.
3. You must use the following frame work to implement your tokenizer.
class Tokenizer {
private char [] Buf;
private int cur;
Tokenizer(String infixExpression) {
Buf = infixExpression.toCharArray();
cur = 0;
Token nextToken() {
1. Skip blanks.
2. if (cur>=Buf.length) return null;
3. If the next character is a digit, keep reading until a non-digit is read.
Convert the string of digits into an integer.
String Digits = new String(Buf, start, len);
int num = Integer.valueOf(Digits).intValue();
Create and return an operand.
4. Otherwise, use the next character to create and return an operator.
class Tokenizer {
     private char[] Buf;
     private int cur;
     Tokenizer(String infixExpression) {
          Buf = infixExpression.toCharArray();
          cur = 0;
     Token nextToken() {
          int bufLength = Buf.length;
          Object obj = null;
          // ignore blank space
          while (cur < bufLength && Buf[cur] == ' ') {
               cur++;
          // if given string having only space return null
          if (cur >= Buf.length)
               return null;
          StringBuilder value = new StringBuilder();
          // Iterate through each element of string array and construct an string
          // for consecutive digits
          while (cur < bufLength && Buf[cur] <= '9' && Buf[cur] >= '0') {
               value.append(Buf[cur]);
               cur++;
          // if digits are there convert all digits as an integer value and create
          // operand
          if (value.length() > 0) {
               obj = new Operand(Integer.parseInt(value.toString()));
          // if at cur position no digit is present then create operand with the
          // same non digit value
          else {
               obj = new Operator(Buf[cur]);
               cur++;
          return ((Token) (obj));
package StackAndQueue;
public class Queue {
     private int front;
     private int rear;
     private int capacity;
     private Object S[];
     public Queue() {
          front = 0;
          rear = -1;
          capacity = 100;
          S = new Object[capacity];
     public boolean isEmpty() {
          return S[front] == null;
     public void enqueue(Object obj) {
          int insertionPoint = (rear + 1) % capacity;
          if (S[insertionPoint] == null) {
               S[insertionPoint] = obj;
               rear = insertionPoint;
          } else {
               System.out.println("Queue capacity is full");
     public Object dequeue() {
          if (S[front] != null) {
               Object obj = S[front];
               S[front] = null;
               front = (front + 1) % capacity;
               return obj;
          } else {
               System.out.println("Queue is empty");
               return null;
     public String toString() {
          StringBuilder state = new StringBuilder("[");
          for (int i = front; i < capacity; i++) {
               if (S[i] != null) {
                    state.append(S[i] + ", ");
          for (int i = 0; i < front; i++) {
               if (S[i] != null) {
                    state.append(S[i] + ", ");
          if (state.length() > 1) {
               state.delete(state.length() - 2, state.length() - 1);
          state.append("]");
          return state.toString();
package StackAndQueue;
import java.util.LinkedList;
import java.util.List;
public class Stack {
     List<Object> linkedList = null;
     public Stack() {
          linkedList = new LinkedList<Object>();
     public boolean isEmpty() {
          return linkedList.size() == 0;
     public void push(Object obj) {
          linkedList.add(obj);
     public Object pop() {
          int topIndex = linkedList.size() - 1;
          if (topIndex >= 0) {
               Object obj = linkedList.get(topIndex);
               linkedList.remove(topIndex);
               return obj;
          } else {
               return null;
     public Object top() {
          int topIndex = linkedList.size() - 1;
          if (topIndex >= 0) {
               return linkedList.get(topIndex);
          } else {
               return null;
}

So you want us to do what ?
Edited by: sabre150 on Oct 9, 2012 3:17 PM
Cross posted to http://www.coderanch.com/t/594750/Servlets/java/your-lab-replace-instructor-Tokenizer .

Similar Messages

  • Loading classes and performance

    In most of the cases, when a program requires more than 3 classes from a package, we often write the code as import package.* (e.g. when we need lots of GUI components we often need to import javax.swing.*). But in that package, for example the javax.swing package, it seems that most of the classes from that package are not needed. My question is, If we import each class we need individually, will it improve the performance? Or is it a bad programming style? (import each class individually often needs more than 8 lines of codes or even more!)
    Thanks in advance. Davidson

    Well...when you design your code you will have a very good idea of what classes and what packages you will need to use when you actually write your programs. When you write your program, if you specifically know that you will be using just two classes of a particular package then there is absolutely no point at all in you including statements importing the entire package. But you have to be careful.
    That is the reason why a programmer should spend a lot of time in the design rather than jumping into coding. When you have your design on paper in all details, you will know your program as a whole thoroughly. Then you will get a chance to think about optimization techniques for your code. Of course, including an entire package does no harm to your program but...unless you would be using a lot of classes in a package, be specific because this will improve your final code documentation...any documentation explaining your code for that matter. Besides, there is always a difference between a practise that is OK and a good practise :-)
    Vijay :-)

  • Drawing class and package

    My program is about drawing class diagram,package,object and interface�
    I have just done only for package and class diagram
    When I click on the classdiagram icon from my toolbox, it draws a class diagram,but when I then click on the package icon, a package is drawn but the class diagram disappears�..and when I then click again on the classdiagram icon, the package disappears and the previous class diagram reappears,,,,so why??/
    What is the problem?? Is it wiz the viewport??? How can I draw both a class and a package�
    IN MY MAIN MENU I INCLUDE THIS CODE:
    public MainMenu (String title,ProjectDoc doc) {
         super (title,null);
         setResizable(true);
         doc = new ProjectDoc(this);
         this.doc = doc;
         classView = new ClassView(doc,this);
         packageView = new PackageView(doc,this);
              Container content = getContentPane();
        content.setLayout(new BorderLayout());
        JToolBar toolBar = new JToolBar();
        content.add (toolBar, BorderLayout.NORTH);
         classView.setPreferredSize (new Dimension(6000,3500));
         packageView.setPreferredSize(new Dimension(6000,3500));
        drawingPane = new JScrollPane (
                       ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        drawingPane.setViewportView(classView);
      drawingPane.setViewportView(packageView);plzzz help me it is very urgent

    Hi,
    call chapter4.Drawing.class
    <applet code="chapter4.Drawing.class" width="100"
    height="100"> </applet>Regards,
    Ram

  • Will reinstalling Lion via the Lion recovery partition cause you to loose all of your applications, documents, etc or does it just replace the Lion operating system and leave everything else untouched?

    Will reinstalling Lion via the Lion recovery partition cause you to loose all of your applications, documents, etc or does it just replace the Lion operating system and leave everything else untouched?

    The latter. I cant tell you how many times I've reinstalled lion! all your apps will be fine!
    Things that will change are system graphics if you altered them with something like candybar or did it manually.
    Having said that, you should always backup your stuff with time machine incase something does happen.
    This is a very important step which will insure the safety of your files while doing things like updating or installing the OS.
    Please exercise caution when doing things with a Hard Drive.

  • Can someone tell me how many seconds the cross fade is when running your nano in that mode? I teach spin class and want to know how much time I'm losing in that mode.

    can someone tell me how many seconds the cross fade is when running your Ipod 6th Gen nano in that mode? I teach spin class and want to know how much time I'm losing in that mode.

    You aren't losing any time in that mode, but I believe it is a 10 second fade out/fade in.

  • How do I find classes in a package

    Hi,
    I am working on an automation tool which is to be used for testing public API's in our product. The tool is supposed to work this way:
    1. A developer of the API adds a new java file containing the test code for the API in a particular package (which the tool defines). Then he compiles and places the stuff in a jar. There is also a driver class in this same package path defined by the test tool. E.g.
    driver class: com.aaa.bbb.DriverClass
    new API test file: com.aaa.bbb.TestFile
    Now the driver file's job is to find out all the other classes in this particular package and then do some processing. When I tried doing the getPackage() on this driver class to find out about the package I got back a null.
    Question 1: How can I get the package for a particular class (An ugly way to do this would be to strip it out from the classname)
    Question 2: How can I find out what other classes are there in a package?
    Thanks in advance on this.
    Nikhil Singhal
    You can also send me mails at
    [email protected]

    hai
    i have the same problem to finding the classes in package...
    in my case i know the jars name and i have loaded
    classes using code
    ResourceBundle bundle = ResourceBundle.getBundle("source\\ClasssPath");
    StringTokenizer stToke = new StringTokenizer(bundle.getString("ClassPath"),";");
    String temp;
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    while(stToke.hasMoreTokens())
         temp = stToke.nextToken().trim();
    if(temp.endsWith(".jar"))
    JarFile jar = new JarFile(new File(temp));
         Enumeration en = jar.entries();
         String pathStr;
         while(en.hasMoreElements())
         pathStr = en.nextElement().toString();
         System.out.println("pathStr ="+pathStr);
         if(pathStr.endsWith(".class"))
              System.out.println( classLoader.getResource(pathStr));
              System.out.println(classLoader.loadClass(pathStr.substring(0,pathStr.indexOf(".class")).replace('/','.').trim()));
         else classLoader.loadClass(temp);
    here i am getting the classes in that package using code
         String[] filLis = new File("//it//sella//converter//ptlf//startup//").list();
         int length = filLis.length;
         while(length-- >0)
         System.out.println(">"+filLis[length]);
    but its returnign the class when this classes in locale folder(i.e)its not getting the classes in loaded memory...
    so how to retrieve the class files names using package structure name...
    (i am having more then 20 jars files, inthat inside the jar samepackage structue may appear in more then one jars )
    pls help me in this field..
    Thanx

  • Using java class and variables declared in java file in jsp

    hi everyone
    i m trying to seperate business logic form web layer. i don't know i am doing in a right way or not.
    i wanted to access my own java class and its variables in jsp.
    for this i created java file like this
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static void main(String args[]){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                String  str = rs.getString("Name");
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
    }next i created a jsp where i want to access String str defined in java class above.
    <%--
        Document   : fisrt
        Created on : Jul 25, 2009, 3:00:38 PM
        Author     : REiSHI
    --%>
    <%@page import="ris.NewClass"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1><%=str%></h1>
        </body>
    </html>I wanted to print the name field extracted from database by ResultSet.
    but it gives error cannot find symbol str.
    please help me to find right way to do this.
    i am using netbeans ide.

    Very bad approach
    1) Think if your table contains more than one NAMEs then you will get only the last one with your code.
    2) Your String is declared as local variable in the method.
    3) You have not created any object of NewClass nor called the method in JSP page. Then who will call the method to run sql?
    4) Your NewClass contains main method which will not work in web application, it's not standalone desktop application so remove main.
    Better create an ArrayList and then call the method of NewClass and then store the data into ArrayList and return the ArrayList.
    It should look like
    {code:java}
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static ArrayList getNames(){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            ArrayList nameList = new ArrayList();
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                nameList.add(rs.getString("Name"));
               return nameList;
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                   </code><code class="jive-code jive-java"><font>return nameList;</code><code class="jive-code jive-java">
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
          </code><code>return nameList;</code>
    <code class="jive-code jive-java">    }

  • Customizing FD01 and FB70 using PS Class and Characteristics

    Hello SAP Experts
    I have the following issue:
    My client has a requirement where we need to customize the Customer Master  (FD01) screen and the Invoice Posting Screen (FB70). A few additional fields have to be added by creating a separate tab. I was intending to take Abaper's help and do this using user exits but I have been suggested by the cleint to use SAP PS Class and Characteristics feature to do this. Can someone please throw some light on this feature and how can i create custom fields on FD01 and FB70 screens. Is there a way we could customize these screens using PS class and characteristics. Your opinions would be much appreciated.
    Please kindly give your suggestions. Thanks in advance
    Regards,
    Nik

    Joao Paulo,
    Thank you for the response. I have tried to obtain some info from OSS but no luck. Tried all means but there is limited information available.
    Nik

  • Class override, how to create the child class and then the base class

    I started to write a program for a smart DMM, the problem is every version of the DMM the company change the communication commend.
    My idea is to write a child class for every DMM version and every SubVI of the child will override the base class SubVI.
    My problem is, i want first to create one child class and after i will see every thing is work,  start to create the base class. that way i will see if am thinking the right way.
    My question is
    How can i create a child class and then create the base class and configure the SubVi of the child class to be Override of the base class?
    I tried to search in the property of the class but i didn't see nothing.
    Thanks
    Solved!
    Go to Solution.

    This can be done and I've done it on occasion.
    You simply create the base class with the dynamic dispatch methods you require (connector panes need to be identical to thos of the child class).
    Then set the inheritance of the class to inherit from this base class.  If your method is defined as a dynamic dispatch method in the parent, you'll most likely now have some errors (unless your child method was already DD in which case you might just be OK already).
    To change the inheritance of a class, right-click the properties of the class in your project and select properties.  I believe the ineritance tree is at the lower end of the properties.  Click on the "change inheritance" (or something similar) to choose the class from which you now wish to inherit.
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • Find classes in a package

    I'm new to java. What's the best way to find all classes in a standard package (e.g. java.awt). I'm trying to create a list for classes in a package in java.
    thanks

    I guess you're talking about finding them in a running program (like scanning).
    Well, I'm searching a solution for a similar problem.
    Unfortunately, java classes are loaded on demand. That is, if you're not using kung.foo.MyClass in your code, its not known by the vm, so you can't find it using VM calls.
    Since this behavior is the same for packages, you can test this behavior if you're scanning packages using Package.getPackages():
    public class PackageTester {
      // drops the package info on screen.
      public static void listAll (String message , Package [] data) {
        System.out.println ( ) ;
        System.out.println ( message) ;
        System.out.println ( "Amount of passed classes : "+data.length) ;
        for (int i = 0 ; i < data.length; i++)
              System.out.println ( data.toString()) ;
    public static void main (Strinbg [] args) {
    // get a list of all known packages
    Package [] state1 = Package.getPackages() ;
    // load a yet unknown class
    MyClass kong.foo.myClass = new kong.foo.MyClass () ;
    // reload all packages
    Package [] state2 = Package.getPackages() ;
    // print lists to screen
    listAll ("packages before loading MyClass" , state1) ;
    listAll ("packages after loading MyClass" , state2) ;
    Didnt check, but the code should compile.
    This means that, if you want to scan for classes in the vm, you'll have to say the vm which classes you're scanning for. Of course, this is nonsense.
    The most complete way is to scan all files starting at the classpath-entries, and looking for .class-files in directories and .jar/.zip-files. This is much work to do, but it seems to be the only useful solution to solve this nasty problem. You could use tools, which surely are available; but its not an elegant solution.
    Sorry.

  • Document Classes and other Questions

    Basically, i am working on an application that will eventually be deployed to the desktop as an AIR application.
    I am wanting to create an Analogue clock and Digital clock with a button that toggles the display between either one when pressed. As well as this, i will be wanting to display the Date below, i am having a number of issues however.
    I have the code sorted for three of the four components, i have not attempted to figure out the button thus far as i would be more than happy to have the digital clock, analogue clock and date all being displayed on a drag and drop desktop application first. When i say i have it sorted, i have a fully working analogue clock which i have managed to display on the desktop through air on its lonesome, however, i did not include the drag and drop function. For the digital clock and date components i am not sure how to configure them into document classes. The main issue i am having is i do not know if you can reference a dynamic text box within a movie clip to a document class.
    This is the code to show the date
    [code]{
    var currentTime:Date = new Date();
    var month:Array = new Array("January","February","March","April","May","June","July","August","September","Octo ber","November","December");
    var dayOfWeek:Array = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    date_text.text = dayOfWeek[currentTime.getDay()] + " " + currentTime.getDate() + " " + month[currentTime.getMonth()] + " " + currentTime.getFullYear();
    [/code]
    I have put the actionscript frame inside the movie clip file, and i have given both the movie clip, and the dynamic text box within the movie clip the instance name "date_text".
    Basically, i am just struggling in how to put this code into a working document class, since the digital clock and date functions are both, some what similar, i feel the solution to one will more than likely lead to me discovering the solution for the other.
    The other problem i am having, i do not know how i will display all of the components on one air application. I am assuming, that you create one other document class file which links the other four together? i have tried to do this by just linking a new FLA file with the analogue clock, but it does not work. The code for that is below.
    [code]package
              import flash.events.Event;
              import flash.display.MovieClip;
              public class time1 extends MovieClip
                        public var now:Date;
                        public function time1()
                                  // Update screen every frame
                                  addEventListener(Event.ENTER_FRAME,enterFrameHandler);
                        // Event Handling:
                        function enterFrameHandler(event:Event):void
                                  now = new Date();
                                  // Rotate clock hands
                                  hourHand_mc.rotation = now.getHours()*30+(now.getMinutes()/2);
                                  minuteHand_mc.rotation = now.getMinutes()*6+(now.getSeconds()/10);
                                  secondHand_mc.rotation = now.getSeconds()*6;
    [/code]
    That is the original clock document class (3 Movie clips for the moving hands, and the clock face is a graphic, which i may have to reference somehow below)?
    [code]package
              import flash.display.MovieClip;
              public class main extends MovieClip
                        public var hourHand_mc:time1;
                        public var minuteHand_mc:time1;
                        public var secondHand_mc:time1;
                        public function main()
                                  hourHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  hourHand_mc.x = 75;
                                  hourHand_mc.y = 75;
                                  minuteHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  minuteHand_mc.x = 75;
                                  minuteHand_mc.y = 75;
                                  secondHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  secondHand.x = 75;
                                  secondHand.y = 75;
    }[/code]
    This is my attempt at creating the main document class in a seperate FLA file to attempt to load the analogue clock, and later on the Digital Clock, Date Function and Toggle Display button in the same AIR application.
    Any help on this is much appreciated, i have been reading up a lot on it through tutorials and the like, but i can't seem to fully grasp it.

    why do you have code in a movieclip?
    if you want to follow best practice and use a document class you should remove almost all code from timelines.  the only timeline code that might be reasonably used would be a stop() on the first frame of multiframe movieclips.
    so, you should have a document class.  that could contain all your code but it would be better to just have your document class create your 2 clocks and date objects and possibly manage toggling between the two clocks.  you could have a separate class the tracks the time and date and that class is used by your two clock classes and your date class.

  • I have been getting java.lang.ClassNotFoundException: ZeroApplet.class and java.lang.ClassNotFoundException: JavaToJS.class crashes with JRE version 1.6.0_26-b03-384-10M3425 VM executing a Java Applet. Is Apple aware of this problem? No longer supported?

    My web page uses a Java Applet to allow my visitors to replay chess games; the Chess Viewer Deluxe applet was written by Nikolai Pilafov some time ago and has been working properly for some time (until recently). I don't monitor this part of my site regularly so I am not sure when it began to fail. On his web site [http://chesstuff.blogspot.com/2008/11/chess-viewer-deluxe.html] he has a link to check LiveConnect object functionality (which fails for OBJECT tags). His recommendation is to "seek platform specific support which might be available from the JRE developers for your platform".
    I have been getting java.lang.ClassNotFoundException: ZeroApplet.class and java.lang.ClassNotFoundException: JavaToJS.class crashes with JRE version 1.6.0_26-b03-384-10M3425 VM executing a Java Applet. Until I checked the LiveConnect object functionality, I was unable to identify the source of the console error messages. This does seem to be the smoking gun.
    Is Apple aware of this problem? Are these classes no longer supported? Has anyone else had this problem? You can attempt to recreate the problem locally by going to my web page: http://donsmallidge.com/DonSmallidgeChess.html
    Thanks in advance for any help you can provide!
    Abbreviated Java Console output:
    Java Plug-in 1.6.0_26
    Using JRE version 1.6.0_26-b03-384-10M3425 Java HotSpot(TM) 64-Bit Server VM
    load: class ZeroApplet.class not found.
    java.lang.ClassNotFoundException: ZeroApplet.class
        at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:211)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:144)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:662)
        at sun.applet.AppletPanel.createApplet(AppletPanel.java:807)
        at sun.plugin.AppletViewer.createApplet(AppletViewer.java:2389)
        at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
        at sun.applet.AppletPanel.run(AppletPanel.java:368)
        at java.lang.Thread.run(Thread.java:680)
    load: class JavaToJS.class not found.
    java.lang.ClassNotFoundException: JavaToJS.class
        at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:211)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:144)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:662)
        at sun.applet.AppletPanel.createApplet(AppletPanel.java:807)
        at sun.plugin.AppletViewer.createApplet(AppletViewer.java:2389)
        at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
        at sun.applet.AppletPanel.run(AppletPanel.java:368)
        at java.lang.Thread.run(Thread.java:680)

    I just went up to check the LiveConnect object functionality page AND IT WORKED THIS TIME! I must confess, this is very mysterious. I will do some more checking and reply here if I can determine why it is working now (and more importantly, why it didn't work before).

  • Difference between abstract class and the normal class

    Hi...........
    can anyone tell me use of abstract class instead of normal class
    The main doubt for me is...
    1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../

    Class vs. interface
    Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
    For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
    With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
    This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
    Interface vs. abstract class
    Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
    Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

  • What is the difference between document class and normal class

    Hi,
    Please let me know what is the difference between document class and normal class.
    And I have no idea which class should call as document class or call as an object.
    Thanks
    -Actionscript Developer

    the document class is invoked immediately when your swf opens.  the document class must subclass the sprite or movieclip class.
    all other classes are invoked explicitly with code and need not subclass any other class.

  • Got replacement MacBook Pro from Apple and now CS2 won't work. Help!

    After a long story of woe, which is too long to get into now, Apple ended up replacing my near-dead two-year old computer with a new MacBook Pro. (Yay, Apple!) They imaged my old drive, and put it on the new computer, including the applications. I transferred over my CS2 Suite, but now I'm getting Space Monkey, and my Illustrator will start loading and then shut itself down. Since I got the original CS2, I've moved and moved and moved again, and the disks are no where to be found.
    Does anyone have any advice about how to get the CS2 Suite up and running again? Am I going to have to call Adobe and plead my case with them for a new install file?
    Help! I have so many files that I need to access.

    Your best option is to reinstall it, and if you don't have the discs you'll need to contact Adobe.
    Otherwise, since CS is not an Apple product, and your issues are not with an Apple product, you should post further questions regarding CS on Adobe's own forums at: http://www.adobeforums.com

Maybe you are looking for

  • Partitioning an external hard drive for Mac and PC

    I want to partition an external hard drive (3TB) into 3 even partitions. I want to use one for PC storage, one for Mac storage and the last for Mac backup. Is this possible and how do I do it?

  • Backorder report, not possible to print Cardname

    Hello, in the PLD template for the backorder report it is not possible to inlcude the Cardname, there is no system variable available. Does anyone have a workaround for this? Thank you in advance. Best regards, Anton Wieser.

  • Routing xml (non-soap) messages in OWSM

    Hi all, Normaly we receive soap message from our business partners. These soap messages are then routed internally (by OWSM) to our services based on content (content based routing). OWSM is used as a proxy. Partners do not refer to a specific servic

  • Collecting plug-in metrics using XML API from Perl?

    Hi all, We are building a plug-in to retrieve metrics over an XML API. The QueryDescriptor of each metric will do a call to the Agent's Perl script. This Perl script will then do the actual XML API call, to retrieve the metric's values. Does anyone h

  • Large log file to add to JList

    Hello, I have a rather large log file (> 250 000 lines) which I would like to add to a JList -- I can read the file okay but, obviously, can't fine a container which will hold that many items. Can someone suggest how I might do this? Thanks.