SW6U2 (C++) wrong code with empty base class

Consider this program:
#include <assert.h>
#include <new>
struct Base1
int i;
struct Base2
Base2()
struct Derived : public Base1, public Base2
int main( int, char** )
int buf[2] = { 0x7F7F7F7F, 0x7F7F7F7F };
assert( sizeof( Derived ) == 4 );
new (buf) Derived;
assert( buf[1] == 0x7F7F7F7F ); // <- failure
The second assert fails, because the second (empty) base class Base2 is placed at offset 4 of Derived. But when the custom Base2 constructor runs it makes implicit something like
memset( this, 0, sizeof( Base2) );
sizeof( empty class ) is 1 and the offset of Base2 is 4. Effect is that the constructor writes to memory that is not owned by the whole object.
This can produce some subtile memory errors.
Joerg
p.s. What is the right way to submit and view bugs for this C++ compiler?

The forum posting software eats some C++ code. To get all the code displayed, you must use "code" brackets, and leave a space after each "<" and before each ">".
I assume your two include statements are these:#include < assert.h >
#include < new > and that the rest of the code displayed correctly.
Under those assumptions, I cannot duplicate the bug using the initial release of C++ 5.3, nor with the latest patch. Please be sure the code you post actually shows the problem, and use the "preview" button to see that the code displays correctly.
If you still see the bug with the code you posted, please run this command
CC -V -c foobar.cc
and tell me what output you get. The file foobar.cc does not need to exist.

Similar Messages

  • How to call a Derived call fucntion with a base class object ?

    Hi all
    i am working on a JNI interface to Java, and in the process of simulating a C++ behaviour in java
    so i need some help form you people, in this regard.
    here is a c++ code, i need a equivalent fucntionality in java , to put it one word, the question is
    how to implement the dynamic_cast functionality in java, as java also has virtual fucntions, i think
    this should be possible, if it is not, what is the alternative
    class Base
    public:
         Base()
         ~Base()
         virtual void F1()
              cout<<"The BASE::F1() is called"<<endl;
         virtual void F2()
              cout<<"The BASE::F2() is called"<<endl;
    class Derived : public Base
    public:
         Derived()
         ~Derived()
         virtual  void F3()
              cout<<"The Derived::F3() is called"<<endl;
         virtual void F4()
              cout<<"The Derived::F4() is called"<<endl;
    Base * GetDerived()
         return new Derived();
    int _tmain(int argc, _TCHAR* argv[])
         Base *ptr = NULL;
                    ptr  = GetDerived();
         Derived *dPtr = dynamic_cast<Derived *>(ptr);
                    dPtr->F3();
    }regards
    pradish

    Just to clarify a point that I consider important--the distinction between references and objects:
    Your subject is: How to call a Derived call fucntion with a base class object ? The answer to that is: You cannot. It is completely impossible in Java. If you have a base class object, the derivced class' methods are not present. On the other hand, if you have a compile-time reference of the parent type, but at runtime it happens to point to an instance of the derived class, then, as pointed out, you can cast the reference. (Note that casting does not apply to objects.)

  • Cg produces wrong code with -O

    We're facing strange problem with Frote 6u1 on sparc. When -O switch is used, compiler performs aggressive optimization and all inline calls are being inlined(and that's good). But seems that under certain circumstances calls are not properly inlined inside exception handler. For instance:
    catch (const OSE::CNewOrderData::CBlockException& _crefNewOrdDataExc) {
    const char* l_cszRejectCode;
    l_cszRejectCode = m_ErrorRepository.ConstructErrorCode(CErrorRepository::eInternalError);
    Definition of the called method:
    inline const char* CErrorRepository::ConstructErrorCode(CErrorRepository::EErrorPrefixes _ePrefixIndex)
    std::strcpy(m_szResultingBuffer,m_Prefixes[_ePrefixIndex].m_cszPrefix);
    return m_szResultingBuffer;
    On execution, application crashes inside strcpy, showing the following call parameters:
    i0 9
    i1 129e78
    i2 9
    i3 4f53
    i4 4f
    i5 1336c
    fp ffbbcae0
    i7 8c2a0
    Apparently strcpy is called with destination buffer address 0x9, that causes access violation. Interesting to notice that 0x9 is the first 32 bit of thrown object (_crefNewOrdDataExc). I've checked generated assembly and seems that code does not initialize $o0 befor making strcpy call. And previous value is being used.
    Removing "-O" from command line eliminates this problem.
    Can anyone comment on this ?

    Thanks for the answer,
    Here environment details:
    Solaris 7 sparc, runtime library patch: 106327-12
    Compilation command: cd release ; CC -I/export/home/vic/OSE/include -I/export/home/vic/OSE/OSELib/include -DINTERNAL_VERSION='"0.9.0.0"' -DSYS_ID_STRING=SunOS_5.7_sparc -D_UNIX_APP_ -DDAEMON -DMMGR_USED_WITH_RWSTL -DNDEBUG -O -sb -i -c /export/home/vic/OSE/src/ogwgate.cc
    It seems the problem is somehow triggered by size/complexity of the compiled code: I tried to remove couple of irrelevant headers and it seems to vanish. Compiler didn't complain about lack of disk/memory. I also recompiled it on Solaris 8 with the same set of Forte-specific patches. Result is the same.

  • Flash Pro is ignoring changes to my base class when publishing / debugging

    Hi,
    I hope this will be in the correct section of the forum.
    I've been working with Actionscript 3 since a while now although most of the time I've just done straightforward coding using Flash Develop.
    This is the first time I'm building a more or less complex project in Flash Pro.
    Here's a quick outline of how the project is structured.
    There is a swf file which holds a large set of components. Things like Buttons, Sliders, complex List components, etc.
    All of them are written from scratch not using any existing components (reason being project requirements).
    As someone with a heavy programming background I've done as little as possible in the timeline / frames, most of my code lives in classes which are attached to the components I've created in Flash Pro.
    These classes handle all the functionality. These classes then usually inherit from a base class where some basic functionality lies that I need across all components.
    The components outlined above are all marked for export and lateron imported into other swf files where they are used.
    So far so good, all that works like a charm.
    Now here's the actual problem.
    Today I needed to make changes to the base class to change some fundamental behaviour across all components that inherit from said base class.
    The change in itself was fairly simple.
    However, every time I now try to debug or publish it will completely ignore any change I've made and use the previous version of my base class?
    I can go as far as completely emptying my base class and every time I debug or publish it will do so using the base class from before. I can see at runtime that it is the previous version because of the behaviour of the inherited components.
    That's what I don't get. Where does it take that version from? I tried clearing the publish cash, to no avail.
    I can pace tracers, nothing. If I add code to the base class and make an error it will complain so when I try to debug or publish but once fixed, it won't use any of it. It's still behaving as if it's using a previous version.
    What makes all this even weirder is that if I take that new code and place it into another class and inherit my components from this one, then the build will use that new verison with the new code. If I switch back to the old base class with exactly the same code inside it will ignore it again and once more behave as if its an older version of it.
    I've been looking around the net but simply can't find what this could be caused by.
    Now, sure, I could simply use a new class and inherit all my components from a different base class but that's rather unpractical.
    What I would like to know is, why does Flash Pro ignore any changes to this class? Is this an issue with how I inherit my component classes from a base class? I kind of doubt it because it has been working like a charm before.
    Could this be a Flash Pro issue?
    This is also not the first time I've come across this problem. The previous time however, after much tinkering, it went away. Today, it didn't. I would really like to get to the bottom of this.
    FYI: I'm running Flash Pro CC. I design my components in Flash Pro and do all my coding in Flash Develop.
    Any help would be greatly appreciated.

    Hmm, my classes live in a subfolder of where my fla files live. (This sub folder again is divided into further folders to organise the code)
    I haven't actually setup any class paths. (default class path is set to .)
    If I set the default class path to the folder where my code lives I get a ton of errors telling my that my package names don't reflect the location of my files.
    edit: That was a mistake on my side. I've set the class path to where my code lives and made sure the package names still match up.
    Unfortunately it still ignores my base class (which lives in a sub folder of the defined class path)

  • Flex/AS3 Best way to construct a derived class instance from an existing base class instance?

    What is the best way to handle the instantiation of a derived class from an existing base class.
    I have a base class which is being created via remote_object [RemoteClass alias] from the server.   I have other specialized classes that are derived from this baseclass, but serialization with the server always happens with the base class.     The base class has meta data that defines what the derived class is, for example
    [RemoteClass (alias="com.myco...')]
    public Class Base
         public var derivedType:String;
         public function Base()
    public Class Derived extends Base
         public "some other data"
         public function Derived()
    In my Cairgorm command which retrieves this object from ther server I want to do this:
    public function result (event: Object):void
        var baseInstance:Base = event.result;
         if (baseInstance.derivedType = "derived")
              var derivedInstance:Derived = new Derived( baseInstance );
    What is the most efficient way of doing this?   It appears to me that doing a deep-copy/clone and instantiation of the derived class is pretty inefficient as far as memory allocation and data movement via the copy.

    Thanks for the assistance.  Let me try to clarify.
    MY UI requires a number of composite classes.    The individual components of the composite classes are being transfered to/from the server at different times depending upone which component has changed state.    The construction of the composite classes from the base class happens in my clients business logic.
    Composition happens in a derived class; but server syncronization happens using the base class.    When I recieve the object from Blazeds through the remote object event, it is in the form of the base class.  I then need to instantiate the derived class and copy the elements of the base class into it (for later composite construction).   And likewise when sending the base class back to the server, I need to upcast the derived class to its base class.   But in this case just a mere upcast does not work.  I actually need to create a new base class and copy the attrbutes into it.  I believe this is limitation of how remoting works on Flex/AS3.
    My question is, what is the best way to turn my base class into it's derived class so further composite construction can take place.   The way I am currently doing it is to create a  load method on the base class, that takes the base class as on argument.  The load function, copies all of the instance attribute references from the base class to the target class.
    public Class Base
         public function Base()
         public function load(fromClass:Base)
        {  //  copy the references for all of the instance attributes from the fromClass to this class }
    Then,  after I recieve the base class from the server.   I create a new derived class and pass the base class into the load function like this:
                for (var i:int=0; i < event.result.length; i++) {
                    var derived:Derived = new Derived();
                    derived.load(event.result[i]);
    The drawbacks of this approach is that it now requires 2 extra instance creations per object serialization.   One on recieving the object from the server and one sending it to the server.    I assume copying references are pretty efficient.  But, there is probably some GC issues.     The worst of it is in code maintenance.   The load function now has to be manually maintained and kept in sync with the server class.
    It would be interesting to hear how others have solved this problem.      The server side is an existing application with around 2M LOC, so changing the code on the server is a non-starter.
    Thanks for your help.

  • Base classes generated by annotation processing

    I'm currently trying to figure out how to best reference code generated by annotation processors from non-generated code (and vice versa). One thing that seems to work is to generate source code for a base class of a hand-written class. If the base class needs to call methods in the hand-written class, it's possible to generate suitable abstract methods. Generated code can be put into separate methods.
    However, during the first round, the generated classes do not exist yet, and javac prints error messages. The compilation eventually succeeds. Is there some way to suppress those error messages? ECJ is worse in this regard, it doesn't produce class files in this case. Is this an ECJ bug, or is this approach to code generation simply not supported (and works with javac just by accident)?

    Is there some kind of meta-specification for JSR 269 that explains the design goals? Not really, only what is here http://jcp.org/en/jsr/detail?id=269
    With such a document, it might also be easier to figure out how processors are supposed to work.JSR 269 is designed to permit solutions to various complex scenarios rather than provide solutions. Those scenarios and their intended solution are not often obvious from the API specs.
    You might like to take a look at https://hickory.dev.java.net/ where I have a project to supply some tooling to assist annotation processor authors, and a wiki to document things. Allocating time to this is not easy, but the 3 packages in the API there are pretty robust. The test cases in source code for those have plenty of examples of some of the more complex design goals, such as the ability to write an annotation processor which works correctly in an incremental compile scenario, when the generated file derives from more than one source file, not all of which may be included in an incremental compile.
    Other than that, if you have any particular questions, just ask in this forum, and Joe (JSR 269 spec lead) or myself should be able to answer them for you.
    Bruce
    Edited by: brucechapman on Feb 4, 2008 1:35 PM

  • How to deserialize xml with structure of abitrary nested layers of base class?

    let say i want to represent arithmetic expression using xml:
    <?xml version="1.0" encoding="utf-8" ?>
    <expr>
    <add>
    <num>10</num>
    <num>20</num>
    </add>
    </expr>
    and here is my classes to represent this:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Test
    public abstract class Evaluable
    public abstract int Eval();
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("expr")]
    public class Expr
    [XmlElement]
    public Evaluable Evaluable { get; set; }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("add")]
    [XmlType("add")]
    public class Add : Evaluable
    [XmlElement]
    public List<Evaluable> Elems { get; set; }
    public override int Eval()
    return Elems.Select(e => e.Eval()).Sum();
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    namespace Test
    [Serializable]
    [XmlRoot("num")]
    [XmlType("num")]
    public class Num : Evaluable
    [XmlText]
    public int Val { get; set; }
    public override int Eval()
    return Val;
    but it doesn't work, and it's reasonable, since Serializer doesn't know any thing about the subclass. but how to make it work?
    here is my deserialization code:
    var serializer = new XmlSerializer(typeof(Expr), new[] { typeof(Add), typeof(Num) });
    Expr expr = null;
    using (var file = new StreamReader("expr.xml"))
    expr = serializer.Deserialize(file) as Expr;

    I think what you want is to set the XmlElement attribute on the container (Elems).
    It can be done if the deserializer can be made aware of all the potential subclasses of the base class.  It's ok to put multiple XmlElement attributes on the container to let the deserializer know about the various subclasses it can deserialize.
    I don't think there's a way to tell the XmlSerializer externally about new types.  I could be wrong.  [If someone shows me how to do that, I'd sure appreciate it!]   [WORKAROUND:  A potential workaround
    is to create a class that contains all the potential children including the class itself and serialize that.  Seems a little like cheating.]
    Here is a complete example:
    [Serializable]
    public class Foo
    [XmlAttribute( "name" )]
    public string name;
    [XmlElement( "Foo", Type = typeof( Foo ) )]
    [XmlElement( "Bar", Type = typeof( Bar ) )]
    public List<Foo> children = new List<Foo>();
    public void Dump( int level )
    ShowProperties( level );
    foreach( var f in children ) {
    f.Dump( level + 1 );
    protected virtual void ShowProperties( int level )
    Console.WriteLine( "{0}{1}", new string(' ', level * 4 ), name );
    [Serializable]
    public class Bar : Foo
    public string stuff;
    protected override void ShowProperties( int level )
    base.ShowProperties( level );
    Console.WriteLine( "{0}{1}", new string(' ', level * 4 ), stuff );
    class Program
    static void Main( string[] args )
    // <Foo name="A">
    // <Bar name="B">
    // <Foo name="D" />
    // <stuff>B's Stuff</stuff>
    // </Bar>
    // <Bar name="C">
    // <stuff>C's Stuff</stuff>
    // </Bar>
    // </Foo>
    // A
    // B
    // B's Stuff
    // D
    // C
    // C's Stuff
    Foo a = new Foo() { name = "A" };
    Bar b = new Bar() { name = "B", stuff="B's Stuff" };
    Bar c = new Bar() { name = "C", stuff="C's Stuff" };
    Foo d = new Foo() { name = "D" };
    a.children.Add( b );
    a.children.Add( c );
    b.children.Add( d );
    XmlSerializer xs = new XmlSerializer( typeof( Foo ) );
    // There:
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces( new[] { XmlQualifiedName.Empty } );
    StringBuilder sb = new StringBuilder();
    using( XmlWriter xw = XmlWriter.Create( sb, new XmlWriterSettings() {
    OmitXmlDeclaration = true,
    Indent = true
    xs.Serialize( xw, a, ns );
    Console.WriteLine( sb.ToString() );
    // And Back Again:
    using( StringReader sr = new StringReader( sb.ToString() ) )
    Foo root = (Foo)xs.Deserialize( sr );
    root.Dump( 0 );

  • Empty Virtual Base Classes

    Calls made by my code to virtual functions within a class hierarchy were ending up elsewhere in the hierarchy; adding a dummy data member to the hierarchy's empty virtual base class removed the problem. Apparently this is a known problem in the Sun Workshop 6 update 1 C++ 5.2 compiler with the above-mentioned workaround. The readme for patch 109508-03 indicates the following problem fix:
    4309374 virtual table layout incorrect for empty virtual bases
    Will this patch remove the misdirected calls to virtual functions or do I have to get the latest compiler release, which is supposed to remove the need for dummy data members in empty virtual base class?

    Due to the fact that Java does not support multiple (implementation) inheritance, the diamon-shaped inheritance issue does not arise with Java, hence there is no need to distinguish between "plain" and "virtual" base class.
    (FYI: "Virtual base class" is C++ lingo.)

  • Error with instance variable and constructor of base class

    I am getting the error on the following statement "protected Point apoint" of by base class. What is causing this problem? See my code:
    package Shapes;
    public abstract class Shapes
         protected Point apoint; / ****error at this line****/
         public void move(double xdelta, double ydelta)
              apoint.x += xdelta;
              apoint.y += ydelta;
    public abstract void distance();
    public abstract void show();
    public String toString()
    return "\nThe starting point is at coordinates ("+x+","+y+")";
    package Shapes;
    public class Lines extends Shapes
    protected Point start;
    protected Point end;
         protected double x;
         protected double y;
         double delta;
         public Lines( final Point apoint, final Point bpoint)
    start.x = apoint.x;
              start.y = apoint.y;
              end.x = bpoint.x;
              end.y = bpoint.y;
    public Lines(double xstart, double ystart, double xend, double yend)
    this.xstart = xstart;
              this.ystart = ystart;
              this.xend = xend;
              this.yend = yend;
         public Lines(double x, double y)
              this.x = x;
              this.y = y;
                   public void distance(final Lines start, final Lines end)
                        delta = abs(Math.sqrt (super.x - start.x) * (super.x - end.x) +
                        (super.y - start.y) * (super.y - end.y));
                   Lines move(Point start, double delta)
                        end.x += delta;
                        end.y += delta;
                        return new Point(end);
    public Lines show()
    g.drawLine( start.x, start.y, end.x, end.y);
    public String toString()
    return super.toString()+ "\n moved distance is("
                   + start + ") : (" + end + ")"
                   +" \n to position(" + start + " ) : (" + end + ")";
    package Shapes;
    public class Rectangle extends Lines
         double delta;
    public Rectangle (Point top_lft_pt, Point bottom_rght_pt)
    super(top_lft_pt, bottom_rght_pt);
    public Rectangle(double x_top_lft, double y_top_lft, double x_bottom_rght, double y_bottom_rght)
    super(x_top_lft, y_top_lft, x_bottom_rght, y_bottom_rght);
         public Rectantgle is_it_diagonal()
              if(top_lft.x > bottom_rght.x && bottom_rght.x < top_lft.x)
                   System.out.println("Point are Not Diagonal");
                   public void distance(double delta)
                        delta = abs(Math.sqrt (top_lft.x - bottom_rght.x) * (top_lft.x - botton_rght.x) +
                        (top_lft.y - bottom_rght.y) * (top_lft.y - bottom_rght.y));
                   public Rectangle move(final Point top_lft_pt, double delta)
                        bottom_rght.x += delta;
                        bottom_rght.y += delta;
                        return new Point(bottom_rght_pt);
                   public void get_top_rght_coords()
                        Point top_rght = new Point();
                        top_rght.x = bottom_rght.x;
                        top_rght.y = top_lft.y;
                   public void get_bottom_left_coords()
                        Point bottom_lft = new Point();
                        bottom_lft.x = top_lft.x;
                        bottom_lft.y = bottom_rght.y;
         public Rectangle show()
                        g.drawLine(top_lft.x, top_lft.y, top_rght_x, top_rght_y);
                        g.drawLine(bottom_lft.x, bottom_lft.y, bottom_rght.x, bottom_rght.y);
                        g.drawLine(top_lft.x, top_lft.y, bottom_lft.x, bottom_lft.y);
                        g.drawLine(top_rght.x, top_rght.y, bottom_rght.x, bottom_rght.y);
    package Shapes;
    public class Circles extends Lines
    protected double radius;
         public double delta;
         protected Point center;
    public Circles(double x, double y, double radians)
    super(x, y);
              radius = radians;
         public Circles(Point acenter)
              center.x = acenter.x;
              center.y = acenter.y;
    public void distance()
    delta = abs(Math.sqrt(super.x - x) * (super.x - x) + (super.y - y) * (super.y -y));
         public Circles move(final Point Circles, double delta)
              return new Point(Circles);
    public void show()
    g.drawOval(Circles.x, Circles.y, radius, radius);
    package Shapes;
    import java .math .*;
    import java.util .Random ;
    public class ShapesDriver
    Shapes[] aShape = new Shapes[10];
    static double range = 101.0;
    static Random r1 = new Random();
    public static void main(String [] args)
    double[][] coords = new double[10][10];
    double[] radians = new double [10];
    Shapes anyShape = {
    new Circles(radians),
    new Lines(coords),
    new Rectangle(coords)
    Shapes aShape; /***error at this line***/
              for(int i = 1; i <= coords.length; i++)
    for(int j = 1; j <= coords.length; j++)
                                                      coords[i][j] = r1.nextDouble () * range;
                                                      radians[j] = r1.nextDouble () * range;
    aShape[i] = anyShape[r1.nextInt(aShape.length)];
    System.exit(1);

    Thanks for your help with this problem. Now I have another problem that I am having a hard time figuring out. My program is using inheritance and polymorphism. I trying to use only one version of methods in the superclass points which extends the shapes class which is the abstract superclass vs. repeating the implementation of the methods (move, show, etc.) in each of the subclasses. The error I am getting is this "declare the class abstract, or implement abstract member 'Point Shapes.move()'. As you see, move is declared abstract and of type point in the Shapes superclass and it's behavior is implemented in the subclass Points extending Shapes. The other subclasses, circle, rectangle and lines will invoke the move method from Points and return a new point object. Why I am I getting the error to declare or implement move when the implementation is in Point?
    Below is code, please help?
    import java .awt .Point ;
    public class ShapesDriver
         public static void main(String args[])
              int count = 0;
              int choice;
              Point start = null;
              Point end = null;
              System.out .println(" 1 i am here");
              start = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              end = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
         System.out .println(" 2 i am here");     
         System.out.println (start);
         System.out.println(end);                         
         for(int i = 0; i <= count; i++)
              System.out .println(" 3 i am here");
              choice = (int)(4.0 * Math.random());
              System.out .println(" 4 i am here");
              System.out.println (choice);     
         switch(choice)
              case 0: //Lines
              System.out .println(" 5 i am here");
              Lines apoint = new Lines((int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                                  (int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              Point coords = new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              break;
              case 1: //Circles
              System.out .println(" 6 i am here");
              Circles center = new Circles((double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0),(double)(Math.random()* 10.0));
              Circles centerpt = new Circles((int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (double)(Math.random()* 10.0));
         break;
              case 2: //Rectangles
         System.out .println(" 7 i am here");
              Rectangle top_lft_pt = new Rectangle ((double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0));
              Rectangle bottom_rgt_pt = new Rectangle ((double)(Math.random()* 10.0),
                   (double)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
         break;
         default:
         System.out .println(" 9 i am here");
         System.out.println("\nInvalid shape choice =" + choice);
         System.exit(0);
         break;
         try
                   System.in.read();
                   catch(java.io.IOException ioe)
    import java .awt .Point ;
    public abstract class Shapes
         private String shape;
         public Shapes(String ashape)
              shape = new String(ashape);
         public abstract Point move();
         public double distance()
              return 0.0;
         public abstract void show();
         public String toString()
              return "\nThis shape is a" + shape;
    import java .awt .Point ;
    public class Rectangle extends Points
         protected Point top_lft;
         protected Point top_rgt;
         protected Point bottom_lft;
         protected double top_lft_x;
         protected double top_lft_y;
         protected double bottom_rgt_x;
         protected double bottom_rgt_y;
         protected Point bottom_rgt;
         protected double delta = 0;
         protected String shape = "Rectangle";
         public Rectangle(double x, double y, double top_lft_x,
                             double top_lft_y, double bottom_rgt_x,
                             double bottom_rgt_y)
              super(x, y);
              top_lft_x = top_lft_x;
              top_lft_y = top_lft_y;
              bottom_rgt_x = bottom_rgt_x;
              bottom_rgt_y = bottom_rgt_y;
         public Rectangle( double x, double y, Point bottom_rgt, Point top_lft)
              super(x, y);
              bottom_rgt_x = bottom_rgt.x;
              bottom_rgt_y = bottom_rgt.y;
              top_lft_x = top_lft.x;
              top_lft_y = top_lft.y;
         public String toString()
              return super.toString() + " coordinates top left= " + top_lft_x + "," + top_lft_y + "and bottom right" +
                   bottom_rgt_x + "," + bottom_rgt_y + ")";
         public void is_it_diagonal()
              if(top_lft_x < bottom_rgt_x && bottom_rgt_x > top_lft_x)
                   System.out.println("Points are Not Diagonal");
              public double distance()
                   distance ();
                   return delta;
              public Point move(Point top_lft)
                   move();
                   bottom_rgt_x += delta;
                   bottom_rgt_y += delta;
                   return top_lft;
              public void get_other_coords()
                   top_rgt.x = bottom_rgt.x;
              top_rgt.y = top_lft.y;
                   bottom_lft.x = top_lft.x;
                   bottom_lft.y = bottom_rgt.y;
              public void show()
                   super.show();
                   System.out.println("new coords are :");
                   System.out .println ("(" + top_lft_x + "," + top_lft_y + ")");
                   System.out .println ("top right(" + top_rgt + ")");
                   System.out .println ("(" + bottom_rgt_x + "," + bottom_rgt_y + ")");
                   System.out .println ("bottom right(" + bottom_rgt + ")");
    import java .awt .Point ;
    public class Points extends Shapes
         protected double delta = 0.0;
         protected double x;
         protected double y;
         protected String ashape = "Points";
         public Points( double x, double y)
              super("Points");
              x = x;
              y = y;
         public Points( Point start)
              super("Points");
              x = start.x;
              y = start.y;          
         public String toString()
              return super.toString() + "References coordinates(" + x + y + ")";
         public double distance(double x1, double y1 )
              return delta =(Math.sqrt(x - x1) * (x - x1) + (y - y1) *
              (y - y1));
         public Point move(Point pts)
              pts.x += delta;
              pts.y += delta;
              return pts;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x+ "," + y + ")");
    import java .awt .Point ;
    public class Lines extends Points
         double delta = 0;
         protected double x;
         protected double y;
         protected String ashape = "Lines";
         public Lines( double x1, double y1, double x, double y)
              super(x1,y1);
              x = x;
              y = y;
         public Lines(Point start, Point end)
              super(start);
              x = end.x;
              y = end.y;
         public String toString(Point end)
              return super.toString() + "line points = (" + x + "," + y +
                   "(" + end + ")";
         public double distance()
              distance ();
              return delta;
         public Point move(Point lines)
              move ();
              return lines;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x + "," + y + ")");
    import java .awt .Point ;
    public class Circles extends Points
    protected double radius;
    protected double xcenter;
    protected double ycenter;
    protected String ashape = "Circle";
         public Circles( double x, double y, double cx, double cy, double radians)
              super(x, y);
              xcenter = cx;
              ycenter = cy;
              radius = radians;
         public Circles( Point acenter, Point ref, double radians)
              super(ref);
              xcenter = acenter.x;
              ycenter = acenter.y;
              radius = radians;
         public String toString(Point ref)
              return super.toString() + " reference points (" +
                   ref + ")" +
                   "center coordinates (" + xcenter + "," + ycenter + ")";
              public double distance(Point ref)
                   return (Math.sqrt(ref.x - xcenter) * (ref.x - xcenter)
                             + (ref.y - ycenter) *
              (ref.y - ycenter));
              public Point move(Point center)
                   move();
                   return center;
              public void show()
                   System.out.println("This shape is a" + ashape + "(" +
                                  "(" + xcenter + "," + ycenter + ")");

  • Please! help me with this wrong code, where is mistake

    please! help me with this wrong code, where is mistake?
    import java.util.Stack;
    public class KnightsTour {
    Vars locs[];
    private int size, max=1, d=0, board[][];
    public KnightsTour(int x,int y, int newSize)
         size=newSize;
         locs=new Vars[size*size+1];
         for(int n=1;n<=size*size;n++)
              locs[n]=new Vars();
         board=new int[size+1][size+1];
         for(int n=1;n<=size;n++)
              for(int n2=1;n2<=size;n2++)
                   board[n][n2]=0;
         locs[max].x=x;
         locs[max].y=y;
         locs[max].d=1;
         board[x][y]=max;
         max++;
    class Vars{
         int x;
         int y;
         int d;
    public void GO()
         int n=0;
         while(max<=size*size)
              n++;
              d++;
              if(d>8)
                   max--;
                   board[locs[max].x][locs[max].y]=0;
                   d=locs[max].d+1;
              move();
         printBoard();
    public void move()
         int x=locs[max-1].x, y=locs[max-1].y;
         switch(d)
         case 1:x--;y-=2;break;
         case 2:x++;y-=2;break;
         case 3:x+=2;y--;break;
         case 4:x+=2;y++;break;
         case 5:x++;y+=2;break;
         case 6:x--;y+=2;break;
         case 7:x-=2;y++;break;
         case 8:x-=2;y--;break;
         //System.out.println(" X: "+x+" Y: "+y+" |"+max);
         if((x<1)||(x>size)||(y<1)||(y>size)){}
         else if(board[x][y]!=0){}
         else
              locs[max].x=x;
              locs[max].y=y;
              locs[max].d=d;
              board[x][y]=max;
              max++;
              d=0;
              //printBoard();
    public void printBoard()
         for(int n=1;n<=size;n++)
              for(int n2=1;n2<=size;n2++)
                   if(board[n2][n]<10)
                        System.out.print(board[n2][n]+" ");
                   else
                        System.out.print(board[n2][n]+" ");
              System.out.println();
         //System.out.println();
         System.out.println();
         public static void main (String[]args){
              KnightsTour k = new KnightsTour(1,1,8);
         }

    public class KnightsTour {
        Vars locs[];
        private int size,  max = 1,  d = 0,  board[][];
        public static void main (String[] args) {
            KnightsTour k = new KnightsTour (1, 1, 8);
            k.GO ();
        public KnightsTour (int x, int y, int newSize) {
            size = newSize;
            locs = new Vars[size * size + 1];
            for (int n = 1; n <= size * size; n++) {
                locs[n] = new Vars ();
            board = new int[size + 1][size + 1];
            for (int n = 1; n <= size; n++) {
                for (int n2 = 1; n2 <= size; n2++) {
                    board[n][n2] = 0;
            locs[max].x = x;
            locs[max].y = y;
            locs[max].d = 1;
            board[x][y] = max;
            max++;
        class Vars {
            int x;
            int y;
            int d;
        public void GO () {
            int n = 0;
            while (max <= size * size) {
                n++;
                d++;
                if (d > 8) {
                    max--;
                    board[locs[max].x][locs[max].y] = 0;
                    d = locs[max].d + 1;
                move ();
            printBoard ();
        public void move () {
            int x = locs[max - 1].x, y = locs[max - 1].y;
            switch (d) {
                case 1:
                    x--;
                    y -= 2;
                    break;
                case 2:
                    x++;
                    y -= 2;
                    break;
                case 3:
                    x += 2;
                    y--;
                    break;
                case 4:
                    x += 2;
                    y++;
                    break;
                case 5:
                    x++;
                    y += 2;
                    break;
                case 6:
                    x--;
                    y += 2;
                    break;
                case 7:
                    x -= 2;
                    y++;
                    break;
                case 8:
                    x -= 2;
                    y--;
                    break;
    //System.out.println(" X: "x" Y: "y" |"+max);
            if ((x < 1) || (x > size) || (y < 1) || (y > size)) {
            } else if (board[x][y] != 0) {
            } else {
                locs[max].x = x;
                locs[max].y = y;
                locs[max].d = d;
                board[x][y] = max;
                max++;
                d = 0;
    //printBoard();
        public void printBoard () {
            for (int n = 1; n <= size; n++) {
                for (int n2 = 1; n2 <= size; n2++) {
                    if (board[n2][n] < 10) {
                        System.out.print (board[n2][n] + " ");
                    } else {
                        System.out.print (board[n2][n] + " ");
                System.out.println ();
    //System.out.println();
            System.out.println ();
    }formatting ftw.
    If you call GO () you get in an infinite loop. max gets decreased, and it loops while max is smaller then or equal to size * size. Is your looping logic correct ?

  • How to expose and code the event handlers of a base class?

    I have created a class that inherits NumericUpDown. When I instantiate an object from that class, I can make it visible and have it appear on my form just like any other NUD. How can I get that instantiated object to expose the event handlers of its base
    class, the NUD in this case, so that, for example, I can tell the client what action to take when the value of the instantiated object changes?
    Thanks for your help.

    I am not sure exactly what you mean.  Are you adding your NUD controls to the Form at design time from the toolbox or adding them in code at run time?  If you are adding them to the form from the toolbox then you access the events the same way
    you would a standart NUD control.   If it is at runtime and you have a fixed amount of them you are going to add then you can declare them Class Scoped using the
    WithEvents keyword which will let you access all their events.
    Public Class Form1
    Private WithEvents Nud1 As New NUD
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.Controls.Add(Nud1)
    End Sub
    Private Sub Nud1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Nud1.ValueChanged
    Me.Text = Nud1.Value.ToString
    End Sub
    End Class
    Public Class NUD
    Inherits NumericUpDown
    'Your custom code to make it work how you want...
    End Class
     If this is not what you are doing then you may need to explain a bit more and show the code you are using so we understand better.
    If you say it can`t be done then i`ll try it

  • Base classes with Collection attributes

    I have a question. Suppose I have a base class A, an abstract base class
    to be exact, and subclasses B and C. Assume A has an attribute of
    Collection type, let's call it collectionImpl. Now I would like subclasses
    B and C to be able to have elements of different types along the lines of
    what I've outlined below.
    Strictly speaking, class A wouldn't have to be PC, since I primarily care
    of B and C but I wanted to show the structure.
    <class name="A" persistence-capable-superclass="A">
    <field name="collectionImpl">
    <collection element type="someType"/>
    </field>
    </class>
    <class name="B" persistence-capable-superclass="A">
    <field name="collectionImpl">
    <collection element type="someOtherType"/>
    </field>
    </class>
    So, how would one express this?
    Scott

    Understood. Now for bit more clarification. Given my earlier example, what
    if classes A, B and C implement the java.util.Collection interface. Does
    Kodo have in issue with that? I know Kodo has this ProxyCollection stuff
    but I don't really want to do that, nor do I think I really need to given
    what I'm trying to accomplish.
    The issue I'm having now is that the Kodo Enhancer is complaining that no
    element-type is declared when I have an attribute of class type B for
    example (implementing java.util.Collection) even though an element type is
    declared for the that actual Collection object held in the base class of B
    (A).
    <class name="A" requires-extent="false">
    <field name="impl">
    <collection element-type="SomeType"/>
    <extension vendor-name="kodo" key="ordered" value="true"/>
    </field>
    </class>
    <class name="B" persistence-capable-superclass="A"
    requires-extent="false"/>
    Class "A" extends java.util.AbstractSet, impl is an instance of
    java.util.Collection.
    All this was working quite well until I made some updates recently
    although the basic implementation is the same. Logically I don't know what
    I might have done to cause the new error message.
    I'm using v2.5.2 BTW.
    Scott
    Stephen Kim wrote:
    The one thing to note is that if you do not make A persistent capable,
    you cannot persist fields -declared- in A or query starting from A.
    Scott A. Leschke wrote:
    Can I acheive the same effect by making A be non-PC and provide a abstract
    protected method that will be used by a to access the collection
    implemented in the sub-classes as you suggest (ie. Collection
    getCollectionImpl())?
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • The definition of base class Application was not found.

    Hello:
    I have been coding in Flash Builder Burrito and publishing to my Xoom for a few weeks. All of a sudden at the end of the day I'm getting this compiler error which says:
    1017: The definition of base class Application was not found.    AppName.mxml    /AppName/src    Unknown    Flex Problem
    I sometimes hit the wrong key with I try to copy and paste and all of a sudden a new window will open for source of a default component which I never wanted to edit. I'm afraid I somehow deleted or modified the default class defnition of Application?
    I don't understand why this would come out of the blue, I was working on a function within a class that was drawing points  ... Then all off a sudden I'm getting this error and it's driving me nuts.
    I tried to reinstall FB Burrito on my Mac, but after all that work it still says the same thing. Wouldn't it replace the default class defs?
    Please help!

    Wow, some really strange behavior.
    OK, so here is what I'm going through. I reinstall, import the project and compiles.
    Then I uncomment the new section which contains the following code:
    lineStyle(1.0,0x8ea4bf);
    var line_commands:Vector.<int> = new Vector.<int>();
    line_commands.push(GraphicsPathCommand.LINE_TO, GraphicsPathCommand.LINE_TO, GraphicsPathCommand.LINE_TO, GraphicsPathCommand.LINE_TO);
    var line_coord:Vector.<Number> = new Vector.<Number>();
    line_coord.push(0,0, newW, angle, newW, (newH+angle), 0, newH);
    drawPath(line_commands, line_coord);
    I get 3 diffrent errors, which lead up to the error listed in the topic.
    At first it says that "int" isn't a valid type and it points to this line:
    var line_commands:Vector.<int> = new Vector.<int>();
    Then I take int out so the line looks like this:
    var line_commands:Vector = new Vector();
    Then it says I can't nest classes and it points to the main MXML. I go to the main MXML then the error switches to say "The definition of base class Application was not found.".
    I did figure out how to fix this with out reinstalling. I have to delete the project from my list (making sure to comment out the code above), then re-launch FB Burrito, then re-import the project and it works.
    This is way nuts! I dont understand ... am I crazy?

  • Wrong codes? or maybe I don't understand the instructions

    The instructions said "Write a procedure that will retrieve an
    existing record in Enrollment usiing the student and section Ids
    and set the grade to a specified value. (use update instead of
    insert) and write another procedure that will assign a given
    student a given advisor" I tried but cause I got a lot of
    errors!!! any help would be appreciated just email me at
    [email protected]. thanks!
    create sequence room_seq increment by 1;
    create sequence faculty_seq increment by 1;
    create sequence student_seq increment by 1;
    create sequence section_seq increment by 1;
    create sequence enrollment_seq increment by 1;
    create sequence room_section_seq increment by 1;
    create table course(
    courseNo varchar2(10),
    name varchar2(30),
    credits number,
    constraint course_pk primary key (courseNo));
    insert into course (courseNo, name, credits) values
    ('CIS405','ADVANCED DATABASE', 5);
    insert into course (courseNo, name, credits) values
    ('CIS349','INTRO TO DATABASE', 5);
    COMMIT;
    create table room(
    roomID number,
    bldg char(1) check (bldg IN ('A','B')),
    roomNo varchar2(10),
    maxCapacity number,
    style varchar2(15) check(style IN
    ('LECTURE','LECTURE/LAB','LAB','OFFICE')),
    constraint room_pk primary key (roomID));
    insert into room (roomID, bldg, roomNo, maxCapacity, style)
    values (room_seq.nextval, 'B', '151A', 50, 'LAB');
    insert into room (roomID, bldg, roomNo, maxCapacity, style)
    values (room_seq.nextval, 'B', '151B', 50, 'LAB');
    commit;
    create table faculty(
    facultyID number,
    lname varchar2(30) not null,
    fname varchar2(20) not null,
    dept varchar2(5),
    officeID number,
    phone varchar2(15),
    email varchar2(75),
    rank char(4) check(rank IN ('INST','ASOC','ASST','FULL','SENR')),
    constraint faculty_pk primary key (facultyID),
    constraint faculty_fk foreign key (officeID) references room
    (roomID));
    insert into faculty(facultyID, lname, fname, dept, officeID,
    phone, email, rank) values
    (faculty_seq.nextval, 'CANNON', 'AMY', 'CIS',
    6, '77052149003252', '[email protected]','FULL');
    commit;
    create table equipment(
    equipmentID varchar2(30),
    roomID number,
    type varchar2(20) check(type IN('OVERHEAD PROJECTOR','PORTABLE
    PROJECTOR','LAPTOP CONNECTION','DESKTOP COMPUTER','INTERNET
    CONNECTION')),
    constraint equipment_pk primary key (equipmentID),
    constraint equipment_fk foreign key (roomID) references room
    (roomID));
    INSERT INTO EQUIPMENT (EQUIPMENTID, ROOMID, TYPE) VALUES ('111',
    5, 'DESKTOP COMPUTER');
    INSERT INTO EQUIPMENT (EQUIPMENTID, ROOMID, TYPE) VALUES ('222',
    5, 'OVERHEAD PROJECTOR');
    commit;
    create table student(
    stuID number,
    lname varchar2(30),
    fname varchar2(20),
    street varchar2(100),
    city varchar2(60),
    state char(2),
    zip varchar2(9),
    major varchar2(5) check(major IN
    ('ACCT','ECT','EET','BIS','BSIT','CIS','TCOM')),
    standing varchar2(10) check(standing IN
    ('FRESHMAN','SOPHOMORE','JUNIOR','SENIOR')),
    gpa number(3,2),
    advisor number,
    constraint student_pk primary key (stuID),
    constraint student_FK foreign key (advisor) references faculty
    (facultyID));
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'SMITH', 'HEATHER', 'CIS', 'JUNIOR', 3.8,
    2);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'ELLIOTT', 'DAVE', 'CIS', 'JUNIOR', 3.65,
    2);
    commit;
    create table section(
    sectionID number,
    sectionNo char(1),
    courseNo varchar2(10),
    facultyID number,
    term char(4),
    curSize number,
    maxSize number,
    constraint section_pk primary key (sectionID),
    constraint section_course_fk foreign key (courseNo) references
    course(courseNo),
    constraint section_faculty_fk foreign key (facultyID) references
    faculty(facultyID));
    INSERT INTO SECTION (SECTIONID, SECTIONNO, COURSENO, FACULTYID,
    TERM, CURSIZE, MAXSIZE)
    VALUES (SECTION_SEQ.NEXTVAL, 'T', 'CIS405', 1, '1001', 17, 30);
    INSERT INTO SECTION (SECTIONID, SECTIONNO, COURSENO, FACULTYID,
    TERM, CURSIZE, MAXSIZE)
    VALUES (SECTION_SEQ.NEXTVAL, 'G', 'CIS405', 2, '1001', 24, 30);
    commit;
    create table enrollment(
    stuSectionID number,
    stuID number,
    sectionID number,
    grade char(1) check(grade IN('A','B','C','D','F','I','W')),
    constraint enrollment_pk primary key (stuSectionID),
    constraint enrollment_stu_fk foreign key (stuID) references
    student(stuID),
    constraint enrollment_section_fk foreign key (sectionID)
    references section(sectionID));
    INSERT INTO ENROLLMENT (STUSECTIONID, STUID, SECTIONID) VALUES
    (ENROLLMENT_SEQ.NEXTVAL, 3, 1);
    INSERT INTO ENROLLMENT (STUSECTIONID, STUID, SECTIONID) VALUES
    (ENROLLMENT_SEQ.NEXTVAL, 3, 8);
    commit;
    create table room_section(
    roomSectionID number,
    sectionID number,
    roomID number,
    day char(3) check(day IN
    ('MON','TUE','WED','THU','FRI','SAT','SUN')),
    hour date,
    term char(4),
    constraint room_section_pk primary key (roomSectionID),
    constraint room_section_section_fk foreign key (sectionID)
    references section(sectionID),
    constraint room_section_room_fk foreign key (roomID) references
    room(roomID));
    INSERT INTO ROOM_SECTION (ROOMSECTIONID, SECTIONID, ROOMID, DAY,
    HOUR, TERM)
    VALUES (ROOM_SECTION_SEQ.NEXTVAL, 1, 3, 'MON', TO_DATE('9:30
    AM', 'HH:MI AM'), '1001');
    INSERT INTO ROOM_SECTION (ROOMSECTIONID, SECTIONID, ROOMID, DAY,
    HOUR, TERM)
    VALUES (ROOM_SECTION_SEQ.NEXTVAL, 1, 3, 'MON', TO_DATE('10:30
    AM', 'HH:MI AM'), '1001');
    commit;
    SQL> DESC ENROLLMENT
    Name Null? Type
    STUSECTIONID NOT NULL NUMBER
    STUID NUMBER
    SECTIONID NUMBER
    GRADE CHAR(1)
    SQL> CREATE OR REPLACE PROCEDURE Enrollment(
    2 p_grade IN CHAR(1),
    3 IS
    4 v_stuid NUMBER,
    5 v_sectionid NUMBER;
    6 BEGIN
    7 SELECT student_seq.NEXTVAL
    8 INTO v_stuid
    9 FROM DUAL;
    10 UPDATE student
    11 (stuid,
    12 sectionid,
    13 grade,
    14 SET (v_stuid,
    15 v_sectionid,
    16 UPPER (p_grade),
    17 COMMIT;
    18 DBMS_OUTPUT.PUT_LINE ('Student added');
    19 EXCEPTION
    20 WHEN OTHERS THEN
    21 DBMS_OUTPUT.PUT_LINE ('An error occurred');
    22 END AddStudent;
    23 /
    I got those errors like above!!! I don't understand what the
    instructions said. any assistance would be appreciated!

    David,
    I am afraid that the
    EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE ('An error occurred');
    was my fault. I had intended it as an example to provide only
    minimal syntax where no exception handling whatsoever previously
    existed. Beau is a student and I am trying to guide him in the
    right direction without just writing all of it for him. In
    fact, I am afraid I may have already provided too much code
    without sufficient explanation. For you and others who may wish
    to help, here are the e-mails that provide the background on how
    we got to this point, with the most recent on top, starting with
    the last resonse I sent to him:
    Things that are wrong:
    The instructions say to be sure to use the sequence number for
    the student's ID, so you should not have p_stuID as an input
    parameter. Instead you should create a variable and select the
    student_seq.nextval into the variable from the dual table and
    use that value to populate the stuid column.
    Your input parameters should only have the variable type, not
    the size, so just use varchar2 and number.
    The check constraints only belong in the script that is used to
    create the table, not in your procedure with your input
    parameters, so remove them from the procedure.
    The order and number of your columns you are inserting into and
    values you are inserting must match, so if you insert into fname
    then lname, you need to insert the values p_fname then p_lname.
    You must either have first name then last name in both or last
    name then first name in both, not one way in one and the other
    way in the other.
    The idea is that when you execute the procedure you specify the
    values of the input parameter variable, then use those input
    parameter variables to insert the values into the table. You
    should not be specifying any specific values anywhere in your
    procedure. In other words don't insert 'HEATHER', instead
    insert fname, and so on.
    You should only have one insert statement. Each time the
    procedure is executed, a different set of values will be
    provided, and the same insert statement will be used.
    Additional suggestions:
    Although it is not required, since IN is the default, it is
    generally considered to be a good programming practice to use IN
    with your input parameters. It just makes the code easier to
    read and understand. As you write other code, you will learn to
    use OUT for output parameters and IN OUT for parameters that are
    both input and output parameters.
    It is generally recommended to store all data in upper case,
    that is capital letters, so that it is easier to index and
    search and avoid duplicates and so on. In order to ensure that
    your data is input in upper case, it is a good idea to use the
    UPPER function.
    Different programmers and companies have different standards
    that they use for capitalization, indentation, spacing,
    alignment, and so forth to make their code uniform and easier to
    read. You may want to look at some various styles and see what
    you like or ask what your instructor recommends.
    You should add some sort of exception handling section. For
    example, if someone attempts to insert a value for standing that
    isn't acceptable, then the procedure will fail due to the
    constraints and the student will not be added. You probably
    want to display some sort of message to the user. You might
    also want to display a message if the input is successful.
    When you attempt to compile your program and you receive a
    message that says "Warning: Procedure created with compilation
    errors." or some such thing, then from the SQL> prompt, type
    SHOW ERRORS and it will list the error message number, a brief
    description of the problem, and the line of code that the
    problem occurred on. You can then type LIST and it will list
    the code with line numbers, so that you can tell what line
    number the error message is referring to.
    In the following example, I have fixed the things that were
    wrong, formatted it the way I usually do, and added minimal
    exception handling and messages. There is a lot more that you
    could do. I have also demonstrated how the program can be
    tested and the results of proper input and improper input. In
    the example below, two students are added correctly, then an
    attempt to add another fails because the standing is not valid
    and violates a check constraint, because graduate is not
    acceptable. After each execution of the procedure, I have
    queried the table, so that you can see what was added and what
    was not.
    SQL> CREATE OR REPLACE PROCEDURE AddStudent
    2 (p_fname IN VARCHAR2,
    3 p_lname IN VARCHAR2,
    4 p_major IN VARCHAR2,
    5 p_standing IN VARCHAR2,
    6 p_gpa IN NUMBER)
    7 IS
    8 v_stuid NUMBER;
    9 BEGIN
    10 SELECT student_seq.NEXTVAL
    11 INTO v_stuid
    12 FROM DUAL;
    13
    14 INSERT INTO student
    15 (stuid,
    16 fname,
    17 lname,
    18 major,
    19 standing,
    20 gpa)
    21 VALUES (v_stuid,
    22 UPPER (p_fname),
    23 UPPER (p_lname),
    24 UPPER (p_major),
    25 UPPER (p_standing),
    26 p_gpa);
    27
    28 COMMIT;
    29 DBMS_OUTPUT.PUT_LINE ('Student added');
    30 EXCEPTION
    31 WHEN OTHERS THEN
    32 DBMS_OUTPUT.PUT_LINE ('An error occurred');
    33 END AddStudent;
    34 /
    Procedure created.
    SQL> COLUMN fname FORMAT A15
    SQL> COLUMN lname FORMAT A15
    SQL> SELECT stuid, fname, lname, major, standing, gpa
    2 FROM student
    3 /
    no rows selected
    SQL> SET SERVEROUTPUT ON
    SQL> EXEC AddStudent ('HEATHER', 'SMITH', 'CIS', 'JUNIOR', 3.8)
    Student added
    PL/SQL procedure successfully completed.
    SQL> SELECT stuid, fname, lname, major, standing, gpa
    2 FROM student
    3 /
    STUID FNAME LNAME MAJOR
    STANDING GPA
    1 HEATHER SMITH CIS
    JUNIOR 3.8
    SQL> EXEC AddStudent ('Dave', 'Elliott', 'CIS', 'junior', 3.65)
    Student added
    PL/SQL procedure successfully completed.
    SQL> SELECT stuid, fname, lname, major, standing, gpa
    2 FROM student
    3 /
    STUID FNAME LNAME MAJOR
    STANDING GPA
    1 HEATHER SMITH CIS
    JUNIOR 3.8
    2 DAVE ELLIOTT CIS
    JUNIOR 3.65
    SQL> EXEC AddStudent ('KARL', 'WEBSTER', 'CIS', 'GRADUATE', 3.2)
    An error occurred
    PL/SQL procedure successfully completed.
    SQL> SELECT stuid, fname, lname, major, standing, gpa
    2 FROM student
    3 /
    STUID FNAME LNAME MAJOR
    STANDING GPA
    1 HEATHER SMITH CIS
    JUNIOR 3.8
    2 DAVE ELLIOTT CIS
    JUNIOR 3.65
    SQL>
    I am going home now. Sometimes I get a chance to respond to my
    e-mail daily and sometimes I may not get to it for a week. It
    is better if you post your questions on one of the forums where
    you may get more rapid responses from many people. I have
    provided links to some forums that I browse below. If you have
    internet access, you should be able to just click on them. Some
    may require you to register, but they are all free.
    The following is a link to the Oracle Technology Network forums,
    hosted by Oracle Corporation, where I recommend the SQL and
    PL/SQL discussions.
    http://forums.oracle.com/forums/homepage.jsp
    The following is a link to the PL/SQL forums of the REVEALNET
    site, where noted author Steven Feuerstein is one of the SYSOPS,
    where, for you, I recommend the "Beginner PL/SQL Developer
    Questions" discussions.
    http://PIPETALK.REVEALNET.COM/~PLSQL/LOGIN
    The following is a link to another forum, where I recommend the
    RDBMS, SQL, PL/SQL discussions.
    http://www.orafans.com/cgi-bin/orafans/ubb/Ultimate.cgi?
    action=intro
    I would still like to know where you got my e-mail address, what
    class you are taking, who your instructor is, and so forth.
    Please do let me know.
    Good luck,
    Barbara
    -----Original Message-----
    From:     bseo.ga [SMTP:[email protected]]
    Sent:     Wednesday, December 19, 2001 12:19 AM
    To:     Boehmer, Barbara A.
    Subject:     Re: PL/SQL
    Importance:     High
    what is wrong with the compilation errors?
    CREATE or REPLACE PROCEDURE AddStudent(
    p_stuID number,
    p_lname varchar2(30),
    p_fname varchar2(20),
    p_major varchar2(5) check(major IN
    ('ACCT','ECT','EET','BIS','BSIT','CIS','TCOM')),
    P_standing varchar2(10) check(standing IN
    ('FRESHMAN','SOPHOMORE','JUNIOR','SENIOR')),
    P_gpa number(3,2) IS
    BEGIN
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'SMITH', 'HEATHER', 'CIS', 'JUNIOR', 3.8,
    2);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'ELLIOTT', 'DAVE', 'CIS', 'JUNIOR', 3.65,
    2);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'WEBSTER', 'KARL', 'CIS', 'SENIOR', 3.2,
    2);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'COX', 'STACEY', 'CIS', 'SENIOR', 2.7, 1);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'HOWARD', 'BRIAN', 'CIS', 'JUNIOR', 3.18,
    1);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'DENNIS', 'KELLY', 'CIS', 'SENIOR', 4.0,
    1);
    COMMIT;
    END;
    SQL> /
    Warning: Procedure created with compilation errors.
    ----- Original Message -----
    From: Boehmer, Barbara A. <mailto:[email protected]>
    To: 'bseo.ga' <mailto:[email protected]>
    Sent: Tuesday, December 18, 2001 5:17 PM
    Subject: RE: PL/SQL
    I am not sure what part of it you don't understand.
    The first section that you included is a script that you need to
    copy and run, in order to create the sequences, tables, and data
    that you will need to complete your assignment. You will need
    to edit an empty .sql file, copy the script into the file, save
    the file, then start the file. For example:
    SQL> EDIT test
    Type or copy the script and save the file.
    SQL> START test
    You should see various messages as the items are created. Then
    you can use the following commands to see the tables and
    sequences that you have created:
    SQL> SELECT table_name FROM user_tables;
    SQL> SELECT sequence_name FROM user_sequences;
    To show the structure of an individual table, for example the
    course table:
    SQL> DESC course
    To show the data in an individual table, like the course table:
    SQL> SELECT * FROM course;
    In the second section that you have provided, your instructor is
    asking you to create three different procedures to do three
    different things. To create a procedure, you edit a .sql file,
    type the code to create the procedure, save the file, then start
    the file. I usually make the .sql file name the same as the
    procedure name. So, for example, in number 1, you are asked to
    create a procedure named AddStudent, so you would:
    SQL> EDIT AddStudent
    Type your code.
    Save the file.
    SQL> START AddStudent
    You should receive a message that says:
    Procedure created.
    Then, to execute your procedure:
    SQL> EXEC AddStudent (put your parameter values here)
    The basic syntax for creating a pl/sql procedure is:
    CREATE OR REPLACE PROCEDURE procedure_name
    (put your parameters here)
    AS
    put your variable declarations here;
    BEGIN
    put your code that you want to execute here,
    like insert statements and update statements;
    END procedure_name;
    So, if you are trying to create a procedure to add a new student
    (which means inserting a row into the student table), you will
    need to accept the values (parameters) that you are going to
    insert, then insert them:
    CREATE OR REPLACE PROCEDURE AddStudent
    (p_first .....
    p_last .....
    p_major .....
    p_standing .....
    p_GPA .....)
    AS
    BEGIN
    INSERT INTO student .....;
    END AddStudent;
    I have just given you a starting format and deliberately left
    out a lot, because you will learn more by doing it yourself. I
    hope that makes things a little clearer.
    I would like to know a little more about the class you are
    taking. Please let me know where you are going to school, who
    your instructor is, what is the name of the class you are
    taking, and what book are you using. Also, please let me know
    where you got my e-mail address (from one of the forums?)
    Good luck,
    Barbara
    -----Original Message-----
    From: bseo.ga [mailto:[email protected]]
    Sent: Tuesday, December 18, 2001 5:57 PM
    To: [email protected]
    Subject: PL/SQL
    Importance: High
    I don't understand reading the following instructions from my
    professor and the books. help would be apppreciated.
    -------------create the sequence numbers needed to generate
    primary key values
    create sequence room_seq increment by 1;
    create sequence faculty_seq increment by 1;
    create sequence student_seq increment by 1;
    create sequence section_seq increment by 1;
    create sequence enrollment_seq increment by 1;
    create sequence room_section_seq increment by 1;
    create table course(
    courseNo varchar2(10),
    name varchar2(30),
    credits number,
    constraint course_pk primary key (courseNo));
    insert into course (courseNo, name, credits) values
    ('CIS405','ADVANCED DATABASE', 5);
    insert into course (courseNo, name, credits) values
    ('CIS349','INTRO TO DATABASE', 5);
    COMMIT;
    create table room(
    roomID number,
    bldg char(1) check (bldg IN ('A','B')),
    roomNo varchar2(10),
    maxCapacity number,
    style varchar2(15) check(style IN
    ('LECTURE','LECTURE/LAB','LAB','OFFICE')),
    constraint room_pk primary key (roomID));
    insert into room (roomID, bldg, roomNo, maxCapacity, style)
    values (room_seq.nextval, 'B', '151A', 50, 'LAB');
    insert into room (roomID, bldg, roomNo, maxCapacity, style)
    values (room_seq.nextval, 'B', '151B', 50, 'LAB');
    commit;
    create table faculty(
    facultyID number,
    lname varchar2(30) not null,
    fname varchar2(20) not null,
    dept varchar2(5),
    officeID number,
    phone varchar2(15),
    email varchar2(75),
    rank char(4) check(rank IN
    ('INST','ASOC','ASST','FULL','SENR')),
    constraint faculty_pk primary key (facultyID),
    constraint faculty_fk foreign key (officeID) references room
    (roomID));
    insert into faculty(facultyID, lname, fname, dept, officeID,
    phone, email, rank) values
    (faculty_seq.nextval, 'CANNON', 'AMY', 'CIS',
    6, '77052149003252', '[email protected]','FULL'
    <mailto:'[email protected]','FULL'>);
    commit;
    create table equipment(
    equipmentID varchar2(30),
    roomID number,
    type varchar2(20) check(type IN('OVERHEAD PROJECTOR','PORTABLE
    PROJECTOR','LAPTOP CONNECTION','DESKTOP COMPUTER','INTERNET
    CONNECTION')),
    constraint equipment_pk primary key (equipmentID),
    constraint equipment_fk foreign key (roomID) references room
    (roomID));
    INSERT INTO EQUIPMENT (EQUIPMENTID, ROOMID, TYPE) VALUES ('111',
    5, 'DESKTOP COMPUTER');
    INSERT INTO EQUIPMENT (EQUIPMENTID, ROOMID, TYPE) VALUES ('222',
    5, 'OVERHEAD PROJECTOR');
    commit;
    create table student(
    stuID number,
    lname varchar2(30),
    fname varchar2(20),
    street varchar2(100),
    city varchar2(60),
    state char(2),
    zip varchar2(9),
    major varchar2(5) check(major IN
    ('ACCT','ECT','EET','BIS','BSIT','CIS','TCOM')),
    standing varchar2(10) check(standing IN
    ('FRESHMAN','SOPHOMORE','JUNIOR','SENIOR')),
    gpa number(3,2),
    advisor number,
    constraint student_pk primary key (stuID),
    constraint student_FK foreign key (advisor) references faculty
    (facultyID));
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'SMITH', 'HEATHER', 'CIS', 'JUNIOR', 3.8,
    2);
    INSERT INTO STUDENT (STUID, LNAME, FNAME, MAJOR, STANDING, GPA,
    ADVISOR) VALUES
    (STUDENT_SEQ.NEXTVAL, 'ELLIOTT', 'DAVE', 'CIS', 'JUNIOR', 3.65,
    2);
    commit;
    create table section(
    sectionID number,
    sectionNo char(1),
    courseNo varchar2(10),
    facultyID number,
    term char(4),
    curSize number,
    maxSize number,
    constraint section_pk primary key (sectionID),
    constraint section_course_fk foreign key (courseNo) references
    course(courseNo),
    constraint section_faculty_fk foreign key (facultyID)
    references faculty(facultyID));
    INSERT INTO SECTION (SECTIONID, SECTIONNO, COURSENO, FACULTYID,
    TERM, CURSIZE, MAXSIZE)
    VALUES (SECTION_SEQ.NEXTVAL, 'T', 'CIS405', 1, '1001', 17, 30);
    INSERT INTO SECTION (SECTIONID, SECTIONNO, COURSENO, FACULTYID,
    TERM, CURSIZE, MAXSIZE)
    VALUES (SECTION_SEQ.NEXTVAL, 'G', 'CIS405', 2, '1001', 24, 30);
    commit;
    create table enrollment(
    stuSectionID number,
    stuID number,
    sectionID number,
    grade char(1) check(grade IN('A','B','C','D','F','I','W')),
    constraint enrollment_pk primary key (stuSectionID),
    constraint enrollment_stu_fk foreign key (stuID) references
    student(stuID),
    constraint enrollment_section_fk foreign key (sectionID)
    references section(sectionID));
    INSERT INTO ENROLLMENT (STUSECTIONID, STUID, SECTIONID) VALUES
    (ENROLLMENT_SEQ.NEXTVAL, 3, 1);
    INSERT INTO ENROLLMENT (STUSECTIONID, STUID, SECTIONID) VALUES
    (ENROLLMENT_SEQ.NEXTVAL, 3, 8);
    commit;
    create table room_section(
    roomSectionID number,
    sectionID number,
    roomID number,
    day char(3) check(day IN
    ('MON','TUE','WED','THU','FRI','SAT','SUN')),
    hour date,
    term char(4),
    constraint room_section_pk primary key (roomSectionID),
    constraint room_section_section_fk foreign key (sectionID)
    references section(sectionID),
    constraint room_section_room_fk foreign key (roomID)
    references room(roomID));
    INSERT INTO ROOM_SECTION (ROOMSECTIONID, SECTIONID, ROOMID, DAY,
    HOUR, TERM)
    VALUES (ROOM_SECTION_SEQ.NEXTVAL, 1, 3, 'MON', TO_DATE('9:30
    AM', 'HH:MI AM'), '1001');
    INSERT INTO ROOM_SECTION (ROOMSECTIONID, SECTIONID, ROOMID, DAY,
    HOUR, TERM)
    VALUES (ROOM_SECTION_SEQ.NEXTVAL, 1, 3, 'MON', TO_DATE('10:30
    AM', 'HH:MI AM'), '1001');
    commit;
    The lab notes from my professor said
    1. your system will often need to create a new student. Write
    PL/SQL code for an object named AddStudent that will take values
    for first and last name, major, standing and GPA and add a new
    record in the Student table. Since advisors aren't assigned at
    registration time, we'll add their advisor at a later date.
    Don't worry about the student's address. Be sure to use the
    sequence number for the student's ID.
    2. Write a procedure that will retrieve an existing record in
    Enrollment usiing the student and section Ids and set the grade
    to a specified value. (use update instead of insert)
    3. Write another procedure that will assign a given student a
    given advisor.

  • Warning :: Derived class hides the base class virtual function

    We are porting from CC5.3 to CC5.8 compiler with Sun Studio one compiler. After plenty of hurdles we are in the final stage of removing the warning messages... Amoung the plenty the following one is very common and in different files. Why am I getting this error in 5.8 and not in 5.3 compiler....
    Warning: derived_Object::markRead Hides the virtual function base_Object::markRead(ut_SourceCodeLocation&) const in a virtual base
    From this it is easily understandable that the base class mark read was hidden by derived class markRead... when we drive and override the derived class function.... It is all over the place....
    Thank you,
    Saravanan Kannan
    //public: using xx_Object :: markRead;
    virtual void markRead() const;

    The Sun C++ FAQ discusses the warning message:
    http://developers.sun.com/prodtech/cc/documentation/ss11/mr/READMEs/c++_faq.html#Coding1
    Notice that warnings are not necessarily errors. But I applaud your desire to fix the code so that it generates no warnings. I wish more of our customers could be persuaded to do the same. :-)
    C++ 5.3 issues this warning, by the way. Example:
    struct B { virtual int foo(int); };
    struct D : B { virtual int foo(double); }; // line 2
    D d;
    line 2: Warning: D::foo hides the virtual function B::foo(int).
    If for your particular code you do not see a warning with C++ 5.3, it would be due to a bug in C++ 5.3 that was later fixed.

Maybe you are looking for

  • Error Message no. F5669 in Returns after installing Stack 17

    Greetings Gurus, After applying the Stack 17 upgrade to our system we started getting Error Message no. F5669   Posting date is initial   Message no. F5669   Diagnosis   Fiscal year and period are derived from the posting date.  The posting date, how

  • How to transfer video from iPhone to ipad

    How do you transfer video from iPhone to ipad

  • Copyright a PDF form?

    Am I able to copyright a PDF form built in Livecycle and offer it as part of a billing procedure my company can resell to our product vendors? What are my rights as an author of the document?

  • Javascript or CSS

    I've got a "portfolio" site. The user clicks a thumbnail and javascript basically says: on click; swap image. My image is sometimes horizontal and sometimes verticle. it was a challenge getting this to work in IE, but it works. But now in Opera it al

  • Changing Package for Authorization fields

    HI , I assigned my Authorization fields to $temp while creating them , now i want to change the package and transport them can any one have an idea how to change the package for Authorization Fields. Regards, Abraham