Search Results

Search found 21062 results on 843 pages for 'argos void'.

Page 22/843 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Subterranean IL: Generics and array covariance

    - by Simon Cooper
    Arrays in .NET are curious beasts. They are the only built-in collection types in the CLR, and SZ-arrays (single dimension, zero-indexed) have their own commands and IL syntax. One of their stranger properties is they have a kind of built-in covariance long before generic variance was added in .NET 4. However, this causes a subtle but important problem with generics. First of all, we need to briefly recap on array covariance. SZ-array covariance To demonstrate, I'll tweak the classes I introduced in my previous posts: public class IncrementableClass { public int Value; public virtual void Increment(int incrementBy) { Value += incrementBy; } } public class IncrementableClassx2 : IncrementableClass { public override void Increment(int incrementBy) { base.Increment(incrementBy); base.Increment(incrementBy); } } In the CLR, SZ-arrays of reference types are implicitly convertible to arrays of the element's supertypes, all the way up to object (note that this does not apply to value types). That is, an instance of IncrementableClassx2[] can be used wherever a IncrementableClass[] or object[] is required. When an SZ-array could be used in this fashion, a run-time type check is performed when you try to insert an object into the array to make sure you're not trying to insert an instance of IncrementableClass into an IncrementableClassx2[]. This check means that the following code will compile fine but will fail at run-time: IncrementableClass[] array = new IncrementableClassx2[1]; array[0] = new IncrementableClass(); // throws ArrayTypeMismatchException These checks are enforced by the various stelem* and ldelem* il instructions in such a way as to ensure you can't insert a IncrementableClass into a IncrementableClassx2[]. For the rest of this post, however, I'm going to concentrate on the ldelema instruction. ldelema This instruction pops the array index (int32) and array reference (O) off the stack, and pushes a pointer (&) to the corresponding array element. However, unlike the ldelem instruction, the instruction's type argument must match the run-time array type exactly. This is because, once you've got a managed pointer, you can use that pointer to both load and store values in that array element using the ldind* and stind* (load/store indirect) instructions. As the same pointer can be used for both input and output to the array, the type argument to ldelema must be invariant. At the time, this was a perfectly reasonable restriction, and maintained array type-safety within managed code. However, along came generics, and with it the constrained callvirt instruction. So, what happens when we combine array covariance and constrained callvirt? .method public static void CallIncrementArrayValue() { // IncrementableClassx2[] arr = new IncrementableClassx2[1] ldc.i4.1 newarr IncrementableClassx2 // arr[0] = new IncrementableClassx2(); dup newobj instance void IncrementableClassx2::.ctor() ldc.i4.0 stelem.ref // IncrementArrayValue<IncrementableClass>(arr, 0) // here, we're treating an IncrementableClassx2[] as IncrementableClass[] dup ldc.i4.0 call void IncrementArrayValue<class IncrementableClass>(!!0[],int32) // ... ret } .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } And the result: Unhandled Exception: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at IncrementArrayValue[T](T[] arr, Int32 index) at CallIncrementArrayValue() Hmm. We're instantiating the generic method as IncrementArrayValue<IncrementableClass>, but passing in an IncrementableClassx2[], hence the ldelema instruction is failing as it's expecting an IncrementableClass[]. On features and feature conflicts What we've got here is a conflict between existing behaviour (ldelema ensuring type safety on covariant arrays) and new behaviour (managed pointers to object references used for every constrained callvirt on generic type instances). And, although this is an edge case, there is no general workaround. The generic method could be hidden behind several layers of assemblies, wrappers and interfaces that make it a requirement to use array covariance when calling the generic method. Furthermore, this will only fail at runtime, whereas compile-time safety is what generics were designed for! The solution is the readonly. prefix instruction. This modifies the ldelema instruction to ignore the exact type check for arrays of reference types, and so it lets us take the address of array elements using a covariant type to the actual run-time type of the array: .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 readonly. ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } But what about type safety? In return for ignoring the type check, the resulting controlled mutability pointer can only be used in the following situations: As the object parameter to ldfld, ldflda, stfld, call and constrained callvirt instructions As the pointer parameter to ldobj or ldind* As the source parameter to cpobj In other words, the only operations allowed are those that read from the pointer; stind* and similar that alter the pointer itself are banned. This ensures that the array element we're pointing to won't be changed to anything untoward, and so type safety within the array is maintained. This is a typical example of the maxim that whenever you add a feature to a program, you have to consider how that feature interacts with every single one of the existing features. Although an edge case, the readonly. prefix instruction ensures that generics and array covariance work together and that compile-time type safety is maintained. Tune in next time for a look at the .ctor generic type constraint, and what it means.

    Read the article

  • Relative cam movement and momentum on arbitrary surface

    - by user29244
    I have been working on a game for quite long, think sonic classic physics in 3D or tony hawk psx, with unity3D. However I'm stuck at the most fundamental aspect of movement. The requirement is that I need to move the character in mario 64 fashion (or sonic adventure) aka relative cam input: the camera's forward direction always point input forward the screen, left or right input point toward left or right of the screen. when input are resting, the camera direction is independent from the character direction and the camera can orbit the character when input are pressed the character rotate itself until his direction align with the direction the input is pointing at. It's super easy to do as long your movement are parallel to the global horizontal (or any world axis). However when you try to do this on arbitrary surface (think moving along complex curved surface) with the character sticking to the surface normal (basically moving on wall and ceiling freely), it seems harder. What I want is to achieve the same finesse of movement than in mario but on arbitrary angled surfaces. There is more problem (jumping and transitioning back to the real world alignment and then back on a surface while keeping momentum) but so far I didn't even take off the basics. So far I have accomplish moving along the curved surface and the relative cam input, but for some reason direction fail all the time (point number 3, the character align slowly to the input direction). Do you have an idea how to achieve that? Here is the code and some demo so far: The demo: https://dl.dropbox.com/u/24530447/flash%20build/litesonicengine/LiteSonicEngine5.html Camera code: using UnityEngine; using System.Collections; public class CameraDrive : MonoBehaviour { public GameObject targetObject; public Transform camPivot, camTarget, camRoot, relcamdirDebug; float rot = 0; //---------------------------------------------------------------------------------------------------------- void Start() { this.transform.position = targetObject.transform.position; this.transform.rotation = targetObject.transform.rotation; } void FixedUpdate() { //the pivot system camRoot.position = targetObject.transform.position; //input on pivot orientation rot = 0; float mouse_x = Input.GetAxisRaw( "camera_analog_X" ); // rot = rot + ( 0.1f * Time.deltaTime * mouse_x ); // wrapAngle( rot ); // //when the target object rotate, it rotate too, this should not happen UpdateOrientation(this.transform.forward,targetObject.transform.up); camRoot.transform.RotateAround(camRoot.transform.up,rot); //debug the relcam dir RelativeCamDirection() ; //this camera this.transform.position = camPivot.position; //set the camera to the pivot this.transform.LookAt( camTarget.position ); // } //---------------------------------------------------------------------------------------------------------- public float wrapAngle ( float Degree ) { while (Degree < 0.0f) { Degree = Degree + 360.0f; } while (Degree >= 360.0f) { Degree = Degree - 360.0f; } return Degree; } private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal ) { Vector3 projected_forward_to_normal_surface = forward_vector - ( Vector3.Dot( forward_vector, ground_normal ) ) * ground_normal; camRoot.transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal ); } float GetOffsetAngle( float targetAngle, float DestAngle ) { return ((targetAngle - DestAngle + 180)% 360) - 180; } //---------------------------------------------------------------------------------------------------------- void OnDrawGizmos() { Gizmos.DrawCube( camPivot.transform.position, new Vector3(1,1,1) ); Gizmos.DrawCube( camTarget.transform.position, new Vector3(1,5,1) ); Gizmos.DrawCube( camRoot.transform.position, new Vector3(1,1,1) ); } void OnGUI() { GUI.Label(new Rect(0,80,1000,20*10), "targetObject.transform.up : " + targetObject.transform.up.ToString()); GUI.Label(new Rect(0,100,1000,20*10), "target euler : " + targetObject.transform.eulerAngles.y.ToString()); GUI.Label(new Rect(0,100,1000,20*10), "rot : " + rot.ToString()); } //---------------------------------------------------------------------------------------------------------- void RelativeCamDirection() { float input_vertical_movement = Input.GetAxisRaw( "Vertical" ), input_horizontal_movement = Input.GetAxisRaw( "Horizontal" ); Vector3 relative_forward = Vector3.forward, relative_right = Vector3.right, relative_direction = ( relative_forward * input_vertical_movement ) + ( relative_right * input_horizontal_movement ) ; MovementController MC = targetObject.GetComponent<MovementController>(); MC.motion = relative_direction.normalized * MC.acceleration * Time.fixedDeltaTime; MC.motion = this.transform.TransformDirection( MC.motion ); //MC.transform.Rotate(Vector3.up, input_horizontal_movement * 10f * Time.fixedDeltaTime); } } Mouvement code: using UnityEngine; using System.Collections; public class MovementController : MonoBehaviour { public float deadZoneValue = 0.1f, angle, acceleration = 50.0f; public Vector3 motion ; //-------------------------------------------------------------------------------------------- void OnGUI() { GUILayout.Label( "transform.rotation : " + transform.rotation ); GUILayout.Label( "transform.position : " + transform.position ); GUILayout.Label( "angle : " + angle ); } void FixedUpdate () { Ray ground_check_ray = new Ray( gameObject.transform.position, -gameObject.transform.up ); RaycastHit raycast_result; Rigidbody rigid_body = gameObject.rigidbody; if ( Physics.Raycast( ground_check_ray, out raycast_result ) ) { Vector3 next_position; //UpdateOrientation( gameObject.transform.forward, raycast_result.normal ); UpdateOrientation( gameObject.transform.forward, raycast_result.normal ); next_position = GetNextPosition( raycast_result.point ); rigid_body.MovePosition( next_position ); } } //-------------------------------------------------------------------------------------------- private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal ) { Vector3 projected_forward_to_normal_surface = forward_vector - ( Vector3.Dot( forward_vector, ground_normal ) ) * ground_normal; transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal ); } private Vector3 GetNextPosition( Vector3 current_ground_position ) { Vector3 next_position; // //-------------------------------------------------------------------- // angle = 0; // Vector3 dir = this.transform.InverseTransformDirection(motion); // angle = Vector3.Angle(Vector3.forward, dir);// * 1f * Time.fixedDeltaTime; // // if(angle > 0) this.transform.Rotate(0,angle,0); // //-------------------------------------------------------------------- next_position = current_ground_position + gameObject.transform.up * 0.5f + motion ; return next_position; } } Some observation: I have the correct input, I have the correct translation in the camera direction ... but whenever I attempt to slowly lerp the direction of the character in direction of the input, all I get is wild spin! Sad Also discovered that strafing to the right (immediately at the beginning without moving forward) has major singularity trapping on the equator!! I'm totally lost and crush (I have already done a much more featured version which fail at the same aspect)

    Read the article

  • Code refactoring with Visual Studio 2010 Part-4

    - by Jalpesh P. Vadgama
    I have been writing few post with code refactoring features in Visual Studio 2010. This post also will be part of series and this post will be last of the series. In this post I am going explain two features 1) Encapsulate Field and 2) Extract Interface. Let’s explore both features in details. Encapsulate Field: This is a nice code refactoring feature provides by Visual Studio 2010. With help of this feature we can create properties from the existing private field of the class. Let’s take a simple example of Customer Class. In that I there are two private field called firstName and lastName. Below is the code for the class. public class Customer { private string firstName; private string lastName; public string Address { get; set; } public string City { get; set; } } Now lets encapsulate first field firstName with Encapsulate feature. So first select that field and goto refactor menu in Visual Studio 2010 and click on Encapsulate Field. Once you click that a dialog box will appear like following. Now once you click OK a preview dialog box will open as we have selected preview reference changes. I think its a good options to check that option to preview code that is being changed by IDE itself. Dialog will look like following. Once you click apply it create a new property called FirstName. Same way I have done for the lastName and now my customer class code look like following. public class Customer { private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } private string lastName; public string LastName { get { return lastName; } set { lastName = value; } } public string Address { get; set; } public string City { get; set; } } So you can see that its very easy to create properties with existing fields and you don’t have to change anything there in code it will change all the stuff itself. Extract Interface: When you are writing software prototype and You don’t know the future implementation of that then its a good practice to use interface there. I am going to explain here that How we can extract interface from the existing code without writing a single line of code with the help of code refactoring feature of Visual Studio 2010. For that I have create a Simple Repository class called CustomerRepository with three methods like following. public class CustomerRespository { public void Add() { // Some code to add customer } public void Update() { //some code to update customer } public void Delete() { //some code delete customer } } In above class there are three method Add,Update and Delete where we are going to implement some code for each one. Now I want to create a interface which I can use for my other entities in project. So let’s create a interface from the above class with the help of Visual Studio 2010. So first select class and goto refactor menu and click Extract Interface. It will open up dialog box like following. Here I have selected all the method for interface and Once I click OK then it will create a new file called ICustomerRespository where it has created a interface. Just like following. Here is a code for that interface. using System; namespace CodeRefractoring { interface ICustomerRespository { void Add(); void Delete(); void Update(); } } Now let's see the code for the our class. It will also changed like following to implement the interface. public class CustomerRespository : ICustomerRespository { public void Add() { // Some code to add customer } public void Update() { //some code to update customer } public void Delete() { //some code delete customer } } Isn't that great we have created a interface and implemented it without writing a single line of code. Hope you liked it. Stay tuned for more.. Till that Happy Programming.

    Read the article

  • Android ASync task ProgressDialog isn't showing until background thread finishes

    - by jackbot
    I've got an Android activity which grabs an RSS feed from a URL, and uses the SAX parser to stick each item from the XML into an array. This all works fine but, as expected, takes a bit of time, so I want to use AsyncActivity to do it in the background. My code is as follows: class AddTask extends AsyncTask<Void, Item, Void> { protected void onPreExecute() { pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true); } protected Void doInBackground(Void... unused) { items = parser.getItems(); for (Item it : items) { publishProgress(it); } return(null); } protected void onProgressUpdate(Item... item) { adapter.add(item[0]); } protected void onPostExecute(Void unused) { pDialog.dismiss(); } } Which I call in onCreate() with new AddTask().execute(); The line items = parser.getItems() works fine - items being the arraylist containing each item from the XML. The problem I'm facing is that on starting the activity, the ProgressDialog which i create in onPreExecute() isn't displayed until after the doInBackground() method has finished. i.e. I get a black screen, a long pause, then a completely populated list with the items in. Why is this happening? Why isn't the UI drawing, the ProgressDialog showing, the parser getting the items and incrementally adding them to the list, then the ProgressDialog dismissing?

    Read the article

  • JDK-7 SwingWorker deadlocks?

    - by kd304
    I have a small image processing application which does multiple things at once using SwingWorker. However, if I run the following code (oversimplified excerpt), it just hangs on JDK 7 b70 (windows) but works in 6u16. It starts a new worker within another worker and waits for its result (the real app runs multiple sub-workers and waits for all this way). Did I use some wrong patterns here (as mostly there is 3-5 workers in the swingworker-pool, which has limit of 10 I think)? import javax.swing.SwingUtilities; import javax.swing.SwingWorker; public class Swing { static SwingWorker<String, Void> getWorker2() { return new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { return "Hello World"; } }; } static void runWorker() { SwingWorker<String, Void> worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { SwingWorker<String, Void> sw2 = getWorker2(); sw2.execute(); return sw2.get(); } }; worker.execute(); try { System.out.println(worker.get()); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { runWorker(); } }); } }

    Read the article

  • Android java.lang.VerifyError for private method with annotated argument.

    - by alex2k8
    I have a very simple project that compiles, but can't be started on Emulator. The problem is with this method: private void bar(@Some String a) {} // java.lang.VerifyError The issue can be avoided if annotation removed private void bar(String a) {} // OK or the method visibility changed: void bar(@Some String a) {} // OK public void bar(@Some String a) {} // OK protected void bar(@Some String a) {} // OK Any idea what is wrong with original method? Is this a dalvik bug, or? If some one whould like to experiment with code, here it is: Test.java: public class Test { private void bar(@Some String a) {} public void foo() { bar(null); } } Some.java: public @interface Some {} MainActivity.java: public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Test().foo(); } } Stack trace: ERROR/dalvikvm(1358): Could not find method com.my.Test.bar, referenced from method com.my.Test.foo WARN/dalvikvm(1358): VFY: unable to resolve direct method 11: Lcom/my/Test;.bar (Ljava/lang/String;)V WARN/dalvikvm(1358): VFY: rejecting opcode 0x70 at 0x0001 WARN/dalvikvm(1358): VFY: rejected Lcom/my/Test;.foo ()V WARN/dalvikvm(1358): Verifier rejected class Lcom/my/Test; DEBUG/AndroidRuntime(1358): Shutting down VM WARN/dalvikvm(1358): threadid=3: thread exiting with uncaught exception (group=0x4000fe70) ERROR/AndroidRuntime(1358): Uncaught handler: thread main exiting due to uncaught exception ERROR/AndroidRuntime(1358): java.lang.VerifyError: com.my.Test ERROR/AndroidRuntime(1358): at com.my.MainActivity.onCreate(MainActivity.java:13) ERROR/AndroidRuntime(1358): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) ERROR/AndroidRuntime(1358): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231) ERROR/AndroidRuntime(1358): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284) ERROR/AndroidRuntime(1358): at android.app.ActivityThread.access$1800(ActivityThread.java:112) ERROR/AndroidRuntime(1358): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692) ERROR/AndroidRuntime(1358): at android.os.Handler.dispatchMessage(Handler.java:99) ERROR/AndroidRuntime(1358): at android.os.Looper.loop(Looper.java:123) ERROR/AndroidRuntime(1358): at android.app.ActivityThread.main(ActivityThread.java:3948) ERROR/AndroidRuntime(1358): at java.lang.reflect.Method.invokeNative(Native Method) ERROR/AndroidRuntime(1358): at java.lang.reflect.Method.invoke(Method.java:521) ERROR/AndroidRuntime(1358): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782) ERROR/AndroidRuntime(1358): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540) ERROR/AndroidRuntime(1358): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • Validation with State Pattern for Multi-Page Forms in ASP.NET

    - by philrabin
    I'm trying to implement the state pattern for a multi-page registration form. The data on each page will be accumulated and stored in a session object. Should validation (including service layer calls to the DB) occur on the page level or inside each state class? In other words, should the concrete implementation of IState be concerned with the validation or should it be given a fully populated and valid object? See "EmptyFormState" class below: namespace Example { public class Registrar { private readonly IState formEmptyState; private readonly IState baseInformationComplete; public RegistrarSessionData RegistrarSessionData { get; set;} public Registrar() { RegistrarSessionData = new RegistrarSessionData(); formEmptyState = new EmptyFormState(this); baseInformationComplete = new BasicInfoCompleteState(this); State = formEmptyState; } public IState State { get; set; } public void SubmitData(RegistrarSessionData data) { State.SubmitData(data); } public void ProceedToNextStep() { State.ProceedToNextStep(); } } //actual data stored in the session //to be populated by page public class RegistrarSessionData { public string FirstName { get; set; } public string LastName { get; set; } //will include values of all 4 forms } //State Interface public interface IState { void SubmitData(RegistrarSessionData data); void ProceedToNextStep(); } //Concrete implementation of IState //Beginning state - no data public class EmptyFormState : IState { private readonly Registrar registrar; public EmptyFormState(Registrar registrar) { this.registrar = registrar; } public void SubmitData(RegistrarSessionData data) { //Should Validation occur here? //Should each state object contain a validation class? (IValidator ?) //Should this throw an exception? } public void ProceedToNextStep() { registrar.State = new BasicInfoCompleteState(registrar); } } //Next step, will have 4 in total public class BasicInfoCompleteState : IState { private readonly Registrar registrar; public BasicInfoCompleteState(Registrar registrar) { this.registrar = registrar; } public void SubmitData(RegistrarSessionData data) { //etc } public void ProceedToNextStep() { //etc } } }

    Read the article

  • 'SImple' 2 class Java calculator doesn't accept inputs or do calculations

    - by Tony O'Keeffe
    Hi, I'm trying to get a two class java calculator working (new to java) to work but so far i'm having no success. the two classes are outlined below, calcFrame is for the interface and calEngine should do the actual calculations but i can't get them to talk to one another. i'd really appreciate any assistance on same. Thanks. CalcFrame Code - import java.awt.; import javax.swing.; import javax.swing.border.; import java.awt.event.; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame implements ActionListener { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ public CalcFrame() { makeFrame(); //calc = engine; } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 4)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("3")); contentPane.add(new JButton("4")); contentPane.add(new JButton("5")); contentPane.add(new JButton("6")); contentPane.add(new JButton("7")); contentPane.add(new JButton("8")); contentPane.add(new JButton("9")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(buttonPanel, BorderLayout.CENTER); //status = new JLabel(calc.getAuthor()); //contentPane.add(status, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } /** * An interface action has been performed. * Find out what it was and handle it. * @param event The event that has occured. */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); calc.numberPressed(number); } else if(command.equals("+")) { calc.plus(); } else if(command.equals("-")) { calc.minus(); } else if(command.equals("=")) { calc.equals(); } else if(command.equals("C")) { calc.clear(); } else if(command.equals("?")) { } // else unknown command. redisplay(); } /** * Update the interface display to show the current value of the * calculator. */ private void redisplay() { display.setText("" + calc.getDisplayValue()); } /** * Toggle the info display in the calculator's status area between the * author and version information. */ } CalcEngine - public class CalcEngine { // The calculator's state is maintained in three fields: // buildingDisplayValue, haveLeftOperand, and lastOperator. // The current value (to be) shown in the display. private int displayValue; // The value of an existing left operand. private int leftOperand; /** * Create a CalcEngine. */ public CalcEngine() { clear(); } public int getDisplayValue() { return displayValue; } /** * A number button was pressed. * Either start a new operand, or incorporate this number as * the least significant digit of an existing one. * @param number The number pressed on the calculator. */ public void numberPressed(int number) { if(buildingDisplayValue) { // Incorporate this digit. displayValue = displayValue*10 + number; } else { // Start building a new number. displayValue = number; buildingDisplayValue = true; } } /** * The 'plus' button was pressed. */ public void plus() { applyOperator('+'); } /** * The 'minus' button was pressed. */ public void minus() { applyOperator('-'); } /** * The '=' button was pressed. */ public void equals() { // This should completes the building of a second operand, // so ensure that we really have a left operand, an operator // and a right operand. if(haveLeftOperand && lastOperator != '?' && buildingDisplayValue) { calculateResult(); lastOperator = '?'; buildingDisplayValue = false; } else { keySequenceError(); } } /** * The 'C' (clear) button was pressed. * Reset everything to a starting state. */ public void clear() { lastOperator = '?'; haveLeftOperand = false; buildingDisplayValue = false; displayValue = 0; } /** * @return The title of this calculation engine. */ public String getTitle() { return "Java Calculator"; } /** * @return The author of this engine. */ public String getAuthor() { return "David J. Barnes and Michael Kolling"; } /** * @return The version number of this engine. */ public String getVersion() { return "Version 1.0"; } /** * Combine leftOperand, lastOperator, and the * current display value. * The result becomes both the leftOperand and * the new display value. */ private void calculateResult() { switch(lastOperator) { case '+': displayValue = leftOperand + displayValue; haveLeftOperand = true; leftOperand = displayValue; break; case '-': displayValue = leftOperand - displayValue; haveLeftOperand = true; leftOperand = displayValue; break; default: keySequenceError(); break; } } /** * Apply an operator. * @param operator The operator to apply. */ private void applyOperator(char operator) { // If we are not in the process of building a new operand // then it is an error, unless we have just calculated a // result using '='. if(!buildingDisplayValue && !(haveLeftOperand && lastOperator == '?')) { keySequenceError(); return; } if(lastOperator != '?') { // First apply the previous operator. calculateResult(); } else { // The displayValue now becomes the left operand of this // new operator. haveLeftOperand = true; leftOperand = displayValue; } lastOperator = operator; buildingDisplayValue = false; } /** * Report an error in the sequence of keys that was pressed. */ private void keySequenceError() { System.out.println("A key sequence error has occurred."); // Reset everything. clear(); } }

    Read the article

  • Diamond problem in C++

    - by Jack
    I know the diamond problem. I am using gcc compiler. I have some scenarios I need explanation about. 1) class A{ public: virtual void eat(){cout<<"A eat\n";} }; class B:public A{ public: void eat(){ cout<<"B eat\n";}}; class C:public A{ public: void eat(){ cout<<"C eat\n";}}; class D:public B,C{ public: void eat(){ cout<<"D eat\n";}}; int main() { A * a = new D(); a->eat(); getch(); return 0; } Why doesn't this work? 2) class A{ public: void eat(){cout<<"A eat\n";} }; class B:virtual public A{ public: void eat(){ cout<<"B eat\n";}}; class C:virtual public A{ public: void eat(){ cout<<"C eat\n";}}; class D: public B,C{ public: void eat(){ cout<<"D eat\n";}}; int main() { A * a = new D(); a->eat(); getch(); return 0; } When I do this what happens in the background. How does the ambiguity get removed. Is the concept of vtables involved here?

    Read the article

  • Why do I get two clicked or released signals when using a custom slot for a QPushButton ?

    - by Chris
    here's the main code at first I thought is was the message box but setting a label instead has the same effect. #include <time.h> #include "ui_mainwindow.h" #include <QMessageBox> class MainWindow : public QWidget, private Ui::MainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); void makeSum(void); private: int r1; int r2; private slots: void on_pushButton_released(void); }; MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setupUi(this); } void MainWindow::on_pushButton_released(void) { bool ok; int a = lineEdit->text().toInt(&ok, 10); if (ok) { if (r1+r2==a) { QMessageBox::information( this, "Sums","Correct!" ); } else { QMessageBox::information( this, "Sums","Wrong!" ); } } else { QMessageBox::information( this, "Sums","You need to enter a number" ); } makeSum(); } void MainWindow::makeSum(void) { r1 = rand() % 10 + 1; r2 = rand() % 10 + 1; label->setText(QString::number(r1)); label_3->setText(QString::number(r2)); } int main(int argc, char *argv[]) { srand ( time(NULL) ); QApplication app(argc, argv); MainWindow mw; mw.makeSum(); mw.show(); return app.exec(); } #include "main.moc"

    Read the article

  • c++ function scope

    - by Myx
    I have a main function in A.cpp which has the following relevant two lines of code: B definition(input_file); definition.Print(); In B.h I have the following relevant lines of code: class B { public: // Constructors B(void); B(const char *filename); ~B(void); // File input int ParseLSFile(const char *filename); // Debugging void Print(void); // Data int var1; double var2; vector<char* > var3; map<char*, vector<char* > > var4; } In B.cpp, I have the following function signatures (sorry for being redundant): B::B(void) : var1(-1), var2(numeric_limits<double>::infinity()) { } B::B(const char *filename) { B *def = new B(); def->ParseLSFile(filename); } B::~B(void) { // Free memory for var3 and var 4 } int B::ParseLSFile(const char *filename) { // assign var1, var2, var3, and var4 values } void B::Print(void) { // print contents of var1, var2, var3, and var4 to stdout } So when I call Print() from within B::ParseLSFile(...), then the contents of my structures print correctly to stdout. However, when I call definition.Print() from A.cpp, my structures are empty or contain garbage. Can anyone recommend the correct way to initialize/pass my structures so that I can access them outside of the scope of my function definition? Thanks.

    Read the article

  • How do I call an Obj-C method from Javascript?

    - by gnfti
    Hi all, I'm developing a native iPhone app using Phonegap, so everything is done in HTML and JS. I am using the Flurry SDK for analytics and want to use the [FlurryAPI logEvent:@"EVENT_NAME"]; method to track events. Is there a way to do this in Javascript? So when tracking a link I would imagine using something like <a onClick="flurryTrackEvent("Click_Rainbows")" href="#Rainbows">Rainbows</a> <a onClick="flurryTrackEvent("Click_Unicorns")" href="#Unicorns">Unicorns</a> "FlurryAPI.h" has the following: @interface FlurryAPI : NSObject { } + (void)startSession:(NSString *)apiKey; + (void)logEvent:(NSString *)eventName; + (void)logEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters; + (void)logError:(NSString *)errorID message:(NSString *)message exception:(NSException *)exception; + (void)setUserID:(NSString *)userID; + (void)setEventLoggingEnabled:(BOOL)value; + (void)setServerURL:(NSString *)url; + (void)setSessionReportsOnCloseEnabled:(BOOL)sendSessionReportsOnClose; @end I'm only interested in the logEvent method(s). If it's not clear by now, I'm comfortable with JS but a recovering Obj-C noob. I've read the Apple docs but the examples described there are all for newly declared methods and I imagine this could be simpler to implement because the Obj-C method(s) are already defined. Thank you in advance for any input.

    Read the article

  • Are function-local typedefs visible inside C++0x lambdas?

    - by GMan - Save the Unicorns
    I've run into a strange problem. The following simplified code reproduces the problem in MSVC 2010 Beta 2: template <typename T> struct dummy { static T foo(void) { return T(); } }; int main(void) { typedef dummy<bool> dummy_type; auto x = [](void){ bool b = dummy_type::foo(); }; // auto x = [](void){ bool b = dummy<bool>::foo(); }; // works } The typedef I created locally in the function doesn't seem to be visible in the lambda. If I replace the typedef with the actual type, it works as expected. Here are some other test cases: // crashes the compiler, credit to Tarydon int main(void) { struct dummy {}; auto x = [](void){ dummy d; }; } // works as expected int main(void) { typedef int integer; auto x = [](void){ integer i = 0; }; } I don't have g++ 4.5 available to test it, right now. Is this some strange rule in C++0x, or just a bug in the compiler? From the results above, I'm leaning towards bug. Though the crash is definitely a bug. For now, I have filed two bug reports. All code snippets above should compile. The error has to do with using the scope resolution on locally defined scopes. (Spotted by dvide.) And the crash bug has to do with... who knows. :) Update According to the bug reports, they have both been fixed for the next release of Visual Studio 2010.

    Read the article

  • Using child visitor in C#

    - by Thomas Matthews
    I am setting up a testing component and trying to keep it generic. I want to use a generic Visitor class, but not sure about using descendant classes. Example: public interface Interface_Test_Case { void execute(); void accept(Interface_Test_Visitor v); } public interface Interface_Test_Visitor { void visit(Interface_Test_Case tc); } public interface Interface_Read_Test_Case : Interface_Test_Case { uint read_value(); } public class USB_Read_Test : Interface_Read_Test_Case { void execute() { Console.WriteLine("Executing USB Read Test Case."); } void accept(Interface_Test_Visitor v) { Console.WriteLine("Accepting visitor."); } uint read_value() { Console.WriteLine("Reading value from USB"); return 0; } } public class USB_Read_Visitor : Interface_Test_Visitor { void visit(Interface_Test_Case tc) { Console.WriteLine("Not supported Test Case."); } void visit(Interface_Read_Test_Case rtc) { Console.WriteLine("Not supported Read Test Case."); } void visit(USB_Read_Test urt) { Console.WriteLine("Yay, visiting USB Read Test case."); } } // Code fragment USB_Read_Test test_case; USB_Read_Visitor visitor; test_case.accept(visitor); What are the rules the C# compiler uses to determine which of the methods in USB_Read_Visitor will be executed by the code fragment? I'm trying to factor out dependencies of my testing component. Unfortunately, my current Visitor class contains visit methods for classes not related to the testing component. Am I trying to achieve the impossible?

    Read the article

  • Getting an updated location in Android

    - by jul
    Hi, I'm using the code shown below to get an updated value for location every time a button is clicked. When my activity is resumed I get an update every second, so that when I call getLastKnownLocation I expect to have a location that have been updated in the last second. Is that the correct way to do that? I would expect the onLocationChanged event to be triggered every time I execute a 'geo fix' command (or max after 1s since I request update every 1s), but it's only triggered the first time. Why? Any help/suggestion welcome! Thanks package org.digitalfarm.atable; ... public class Atable extends Activity { private Button mSearchButton; private TextView mytext; private LocationManager locationManager; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mSearchButton = (Button)this.findViewById(R.id.button); mytext = (TextView) findViewById(R.id.dude); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); mSearchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); } }); } //Start a location listener LocationListener onLocationChange=new LocationListener() { public void onLocationChanged(Location loc) { //sets and displays the lat/long when a location is provided String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude(); mytext.setText(latlong); } public void onProviderDisabled(String provider) { // required for interface, not used } public void onProviderEnabled(String provider) { // required for interface, not used } public void onStatusChanged(String provider, int status, Bundle extras) { // required for interface, not used } }; //pauses listener while app is inactive @Override public void onPause() { super.onPause(); locationManager.removeUpdates(onLocationChange); } //reactivates listener when app is resumed @Override public void onResume() { super.onResume(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,100.0f,onLocationChange); } }

    Read the article

  • Concise description of how .h and .m files interact in objective c?

    - by RJ86
    I have just started learning objective C and am really confused how the .h and .m files interact with each other. This simple program has 3 files: Fraction.h #import <Foundation/NSObject.h> @interface Fraction : NSObject { int numerator; int denominator; } - (void) print; - (void) setNumerator: (int) n; - (void) setDenominator: (int) d; - (int) numerator; - (int) denominator; @end Fraction.m #import "Fraction.h" #import <stdio.h> @implementation Fraction -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } @end Main.m #import <stdio.h> #import "Fraction.h" int main(int argc, char *argv[]) { Fraction *frac = [[Fraction alloc] init]; [frac setNumerator: 1]; [frac setDenominator: 3]; printf( "The fraction is: " ); [frac print]; printf( "\n" ); [frac release]; return 0; } From what I understand, the program initially starts running the main.m file. I understand the basic C concepts but this whole "class" and "instance" stuff is really confusing. In the Fraction.h file the @interface is defining numerator and denominator as an integer, but what else is it doing below with the (void)? and what is the purpose of re-defining below? I am also quite confused as to what is happening with the (void) and (int) portions of the Fraction.m and how all of this is brought together in the main.m file. I guess what I am trying to say is that this seems like a fairly easy program to learn how the different portions work with each other - could anyone explain in non-tech jargon?

    Read the article

  • Should I delete the string members of a C++ class?

    - by Bobby
    If I have the following declaration: #include <iostream> #include <string> class DEMData { private: int bitFldPos; int bytFldPos; std::string byteOrder; std::string desS; std::string engUnit; std::string oTag; std::string valType; int idx; public: DEMData(); DEMData(const DEMData &d); void SetIndex(int idx); int GetIndex() const; void SetValType(const char* valType); const char* GetValType() const; void SetOTag(const char* oTag); const char* GetOTag() const; void SetEngUnit(const char* engUnit); const char* GetEngUnit() const; void SetDesS(const char* desS); const char* GetDesS() const; void SetByteOrder(const char* byteOrder); const char* GetByteOrder() const; void SetBytFldPos(int bytFldPos); int GetBytFldPos() const; void SetBitFldPos(int bitFldPos); int GetBitFldPos() const; friend std::ostream &operator<<(std::ostream &stream, DEMData d); bool operator==(const DEMData &d) const; ~DEMData(); }; what code should be in the destructor? Should I "delete" the std::string fields?

    Read the article

  • unresolved token/symbol in MC++ wrapper class calling native code

    - by rediVider
    I'm new to MC++ and have basically no idea what's going on yet. In trying to get this working i've determined many things that don't work, i'm just looking for one of the ways that will work. I have a mc++ class as follows that seems to have to be a "ref" class to allow me to see any methods/properties. public ref class EmCeePlusPlus { static void Open(void) { Testor* t = new Testor(); Testor::Open(); }; }; extern public class Testor { public: Testor() { }; static void Open(void) { int x = 3; int xx = cli_lock(x); }; }; Now, the only reason i created the class Testor, and moved the call to cli_open to it, is because i was getting a unresolved external symbol if i put the same call in the ref class. In this current code, however, I get an uresolved token error and unresolved symbol error ONLY if i have the call to Testor::Open(). If that line is commented then it compiles fine. As it is I get the errors below. cli_lock() is native code that is able to be called externally by other native DLLs with not problems. Any ideas where i should be looking? error LNK2028: unresolved token (0A000056) "extern "C" int __cdecl cli_lock(int)" (?cli_lock@@$$J0YAHH@Z) referenced in function "public: static void __cdecl Giga::Testor::Open(void)" (?Open@Testor@Giga@@$$FSAXXZ) error LNK2019: unresolved external symbol "extern "C" int __cdecl cli_lock(int)" (?cli_lock@@$$J0YAHH@Z) referenced in function "public: static void __cdecl Giga::Testor::Open(void)" (?Open@Testor@Giga@@$$FSAXXZ)

    Read the article

  • problems getting HTTPRiot working

    - by bwizzy
    I've got an iphone app where I'm trying to use HTTPRiot to make some API calls to a web app. Problem is I can't see that none of the HTTPRiot delegate methods are being called. I've got a log in all the delegate methods, and I'm also looking at the webserver log. I see that the URL is being hit. //API.h #import <Foundation/Foundation.h> #include <HTTPRiot/HTTPRiot.h> @interface API : HRRestModel { } +(void)runTest; @end //API.m #import "API.h" @implementation API + (void)initialize { NSLog(@"api initialize"); [self setDelegate:self]; [self setBaseURL:[NSURL URLWithString:@"http://localhost:3000/api"]]; [self setBasicAuthWithUsername:@"demo" password:@"123456"]; NSDictionary *params = [NSDictionary dictionaryWithObject:@"1234567" forKey:@"api_key"]; [self setDefaultParams:params]; }//end initialize +(void)runTest { NSLog(@"api run test"); // Would send a request to http://localhost:1234/api/people/1?api_key=1234567 [self getPath:@"/save_diet" withOptions:nil object:nil]; } +(void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object { NSLog(@"didReturnResource"); } +(void)restConnection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response object:(id)object { NSLog(@"didReceiveResponse"); } +(void)restConnection:(NSURLConnection *)connection didReceiveParseError:(NSError *)error responseBody:(NSString *)body object:(id)object { NSLog(@"didReceiveParseError"); } +(void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object { NSLog(@"didReceiveError"); } +(void)restConnection:(NSURLConnection *)connection didFailWithError:(NSError *)error object:(id)object { NSLog(@"didFailWithError"); } @end //test code [API runTest]; //log output

    Read the article

  • C++, generic programming and virtual functions. How do I get what I want?

    - by carleeto
    This is what I would like to do using templates: struct op1 { virtual void Method1() = 0; } ... struct opN { virtual void MethodN() = 0; } struct test : op1, op2, op3, op4 { virtual void Method1(){/*do work1*/}; virtual void Method2(){/*do work2*/}; virtual void Method3(){/*do work3*/}; virtual void Method4(){/*do work4*/}; } I would like to have a class that simply derives from a template class that provides these method declarations while at the same time making them virtual. This is what I've managed to come up with: #include <iostream> template< size_t N > struct ops : ops< N - 1 > { protected: virtual void DoStuff(){ std::cout<<N<<std::endl; }; public: template< size_t i > void Method() { if( i < N ) ops<i>::DoStuff(); } //leaving out compile time asserts for brevity } struct test : ops<6> { }; int main( int argc, char ** argv ) { test obj; obj.Method<3>(); //prints 3 return 0; } However, as you've probably guessed, I am unable to override any of the 6 methods I have inherited. I'm obviously missing something here. What is my error? No, this isn't homework. This is curiosity.

    Read the article

  • Error with custom Class definition in protocol

    - by Greg
    I'm trying to set up a custom delegate protocol and am getting a strange error that I don't understand. I wonder if someone could point out what I'm doing wrong here (I'm still new to Ob-C and protocol use)... The situation is that I've built my own URLLoader class to manage loading and parsing data from the internet. I'm now trying to set up a protocol for delegates to implement that will respond to the URLLoader's events. So, below is my protocol... #import <UIKit/UIKit.h> #import "URLLoader.h" /** * Protocol for delegates that will respond to a load. */ @protocol URLLoadResponder <NSObject> - (void)loadDidComplete:(URLLoader *)loader; - (void)loadDidFail:(URLLoader *)loader withError:(NSString *)error; @end However, I'm getting the following error for both method signatures: Expected ')' before 'URLLoader' I feel like I must be overlooking something small and silly. Any help folks could offer would be greatly appreciated! Whoops ... it was pointed out that I should include URLLoader.h. Here it is: #import <Foundation/Foundation.h> #import "URLLoadResponder.h" /** * URLLoader inferface. */ @interface URLLoader : NSObject { NSString *name; NSString *loadedData; NSMutableData *responseData; NSObject *delegate; BOOL _isLoaded; } @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSString *loadedData; @property (nonatomic, retain) NSObject *delegate; - (void)loadFromURL:(NSString *)url; - (void)addCompleteListener:(id)observer selector:(SEL)sel; - (void)removeCompleteListener:(id)observer; - (void)parseLoadedData:(NSString *)data; - (void)complete; - (void)close; - (BOOL)isLoaded; + (NSURL *)makeUrlWithString:(NSString *)url; + (URLLoader *)initWithName:(NSString *)name; @end

    Read the article

  • What are the linkage of the following functions?

    - by Derui Si
    When I was reading the c++ 03 standard (7.1.1 Storage class specifiers [dcl.stc]), there are some examples as below, I'm not able to tell how the linkage of each successive declarations is determined? Could anyone help here? Thanks in advance! static char* f(); // f() has internal linkage char* f() { /* ... */ } // f() still has internal linkage char* g(); // g() has external linkage static char* g() { /* ... */ } // error: inconsistent linkage void h(); inline void h(); // external linkage inline void l(); void l(); // external linkage inline void m(); extern void m(); // external linkage static void n(); inline void n(); // internal linkage static int a; // a has internal linkage int a; // error: two definitions static int b; // b has internal linkage extern int b; // b still has internal linkage int c; // c has external linkage static int c; // error: inconsistent linkage extern int d; // d has external linkage static int d; // error: inconsistent linkage UPD: Additionally, how can I understand the statement in the standard, " The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same object name or the same overloading of a function name shall imply the same linkage. Each function in a given set of overloaded functions can have a different linkage, however."

    Read the article

  • Calling an Overridden Method from a Parent-Class Constructor

    - by Vaibhav Bajpai
    I tried calling an overridden method from a constructor of a parent class and noticed different behavior across languages. C++ - echoes A.foo() class A{ public: A(){foo();} virtual void foo(){cout<<"A.foo()";} }; class B : public A{ public: B(){} void foo(){cout<<"B.foo()";} }; int main(){ B *b = new B(); } Java - echoes B.foo() class A{ public A(){foo();} public void foo(){System.out.println("A.foo()");} } class B extends A{ public void foo(){System.out.println("B.foo()");} } class Demo{ public static void main(String args[]){ B b = new B(); } } C# - echoes B.foo() class A{ public A(){foo();} public virtual void foo(){Console.WriteLine("A.foo()");} } class B : A{ public override void foo(){Console.WriteLine("B.foo()");} } class MainClass { public static void Main (string[] args) { B b = new B(); } } I realize that in C++ objects are created from top-most parent going down the hierarchy, so when the constructor calls the overridden method, B does not even exist, so it calls the A' version of the method. However, I am not sure why I am getting different behavior in Java and C#.

    Read the article

  • Project compile perfectly but i get unhandled exception and have no idea why??? any clues?

    - by JB
    get unhandled exception that says: System.NullReferenceException: Object reference not set to an instance of an object. at Eagle_Eye_Class_Finder.GetSchedule.GetDataFromNumber(String ID) in C:\Users\Joshua Banks\Desktop\EET Project\Eagle Eye Class Finder\GetSchedule.cs:line 24 at Eagle_Eye_Class_Finder.Form1.button2_Click(Object sender, EventArgs e) in C:\Users\Joshua Banks\Desktop\EET Project\Eagle Eye Class Finder\Form1.cs:line 196 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.PerformClick() at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData) at System.Windows.Forms.TextBoxBase.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.PreProcessMessage(Message& msg) at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg) at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg) Here is my Get Schedule Class: using System; using System.IO; using System.Data; using System.Text; using System.Drawing; using System.Data.OleDb; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Drawing.Printing; using System.Collections.Generic; namespace Eagle_Eye_Class_Finder { public class GetSchedule { public string GetDataFromNumber(string ID) { IDnumber[] IDnumbers = new IDnumber[3]; foreach (IDnumber IDCandidateMatch in IDnumbers) { if (IDCandidateMatch.ID == ID) { StringBuilder myData = new StringBuilder(); myData.AppendLine(IDCandidateMatch.Name); myData.AppendLine(": "); myData.AppendLine(IDCandidateMatch.ID); myData.AppendLine(IDCandidateMatch.year); myData.AppendLine(IDCandidateMatch.class1); myData.AppendLine(IDCandidateMatch.class2); myData.AppendLine(IDCandidateMatch.class3); myData.AppendLine(IDCandidateMatch.class4); //return myData; return myData.ToString(); } } return ""; } public GetSchedule() { IDnumber[] IDnumbers = new IDnumber[3]; IDnumbers[0] = new IDnumber() { Name = "Joshua Banks", ID = "900456317", year = "Senior", class1 = "TEET 4090", class2 = "TEET 3020", class3 = "TEET 3090", class4 = "TEET 4290" }; IDnumbers[1] = new IDnumber() { Name = "Sean Ward", ID = "900456318", year = "Junior", class1 = "ENGNR 4090", class2 = "ENGNR 3020", class3 = "ENGNR 3090", class4 = "ENGNR 4290" }; IDnumbers[2] = new IDnumber() { Name = "Terrell Johnson", ID = "900456319", year = "Sophomore", class1 = "BUS 4090", class2 = "BUS 3020", class3 = "BUS 3090", class4 = "BUS 4290" }; } public class IDnumber { public string Name { get; set; } public string ID { get; set; } public string year { get; set; } public string class1 { get; set; } public string class2 { get; set; } public string class3 { get; set; } public string class4 { get; set; } public static void ProcessNumber(IDnumber myNum) { StringBuilder myData = new StringBuilder(); myData.AppendLine(myNum.Name); myData.AppendLine(": "); myData.AppendLine(myNum.ID); myData.AppendLine(myNum.year); myData.AppendLine(myNum.class1); myData.AppendLine(myNum.class2); myData.AppendLine(myNum.class3); myData.AppendLine(myNum.class4); MessageBox.Show(myData.ToString()); } } } } Here is my Form 1 class: using System; using System.IO; using System.Data; using System.Text; using System.Drawing; using System.Data.OleDb; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using System.Drawing.Printing; using System.Collections.Generic; namespace Eagle_Eye_Class_Finder { /// This form is the entry form, it is the first form the user will see when the app is run. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button button2; private System.Windows.Forms.DateTimePicker dateTimePicker1; private IContainer components; private Timer timer1; private BindingSource form1BindingSource; public static Form Mainform = null; // creates new instance of second form YOURCLASSSCHEDULE SecondForm = new YOURCLASSSCHEDULE(); public Form1() { InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// Clean up any resources being used. protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.textBox1 = new System.Windows.Forms.TextBox(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.button2 = new System.Windows.Forms.Button(); this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.form1BindingSource = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).BeginInit(); this.SuspendLayout(); // // textBox1 // this.textBox1.BackColor = System.Drawing.SystemColors.ActiveCaption; this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "Text", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, null, "900456317")); this.textBox1.Location = new System.Drawing.Point(328, 280); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(208, 20); this.textBox1.TabIndex = 2; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(258, 410); this.progressBar1.MarqueeAnimationSpeed = 10; this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(344, 8); this.progressBar1.TabIndex = 3; this.progressBar1.Click += new System.EventHandler(this.progressBar1_Click); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlLightLight; this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(680, 400); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(120, 112); this.pictureBox1.TabIndex = 4; this.pictureBox1.TabStop = false; this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Mistral", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image"))); this.button2.Location = new System.Drawing.Point(699, 442); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(78, 28); this.button2.TabIndex = 5; this.button2.Text = "OK"; this.button2.Click += new System.EventHandler(this.button2_Click); // // dateTimePicker1 // this.dateTimePicker1.Location = new System.Drawing.Point(336, 104); this.dateTimePicker1.Name = "dateTimePicker1"; this.dateTimePicker1.Size = new System.Drawing.Size(200, 20); this.dateTimePicker1.TabIndex = 6; this.dateTimePicker1.ValueChanged += new System.EventHandler(this.dateTimePicker1_ValueChanged); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // form1BindingSource // this.form1BindingSource.DataSource = typeof(Eagle_Eye_Class_Finder.Form1); // // Form1 // this.AcceptButton = this.button2; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(856, 556); this.Controls.Add(this.dateTimePicker1); this.Controls.Add(this.button2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.progressBar1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Eagle Eye Class Finder"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// The main entry point for the application. [STAThread] static void Main() { Application.Run(new Form1()); } public void Form1_Load(object sender, System.EventArgs e) { } public void textBox1_TextChanged(object sender, System.EventArgs e) { //allows only numbers to be entered in textbox string Str = textBox1.Text.Trim(); double Num; bool isNum = double.TryParse(Str, out Num); if (isNum) Console.ReadLine(); else MessageBox.Show("Enter A Valid ID Number!"); } public void button2_Click(object sender, System.EventArgs e) { string text = textBox1.Text; Mainform = this; this.Hide(); GetSchedule myScheduleFinder = new GetSchedule(); string result = myScheduleFinder.GetDataFromNumber(text); if (!string.IsNullOrEmpty(result)) { MessageBox.Show(result); } else { MessageBox.Show("Enter A Valid ID Number!"); } } public void dateTimePicker1_ValueChanged(object sender, System.EventArgs e) { } public void pictureBox1_Click(object sender, System.EventArgs e) { } public void progressBar1_Click(object sender, EventArgs e) { //this.progressBar1 = new System.progressBar1(); //progressBar1.Maximum = 200; //progressBar1.Minimum = 0; //progressBar1.Step = 20; } private void timer1_Tick(object sender, EventArgs e) { //if (progressBar1.Value >= 200 ) //{ //progressBar1.Value = 0; //} //return; //} //progressBar1.Value != 20; } } } here is my form 2 class: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Eagle_Eye_Class_Finder { /// /// Summary description for Form2. /// public class YOURCLASSSCHEDULE : System.Windows.Forms.Form { public System.Windows.Forms.LinkLabel linkLabel1; public System.Windows.Forms.LinkLabel linkLabel2; public System.Windows.Forms.LinkLabel linkLabel3; public System.Windows.Forms.LinkLabel linkLabel4; private Button button1; /// Required designer variable. public System.ComponentModel.Container components = null; public YOURCLASSSCHEDULE() { // InitializeComponent(); // TODO: Add any constructor code after InitializeComponent call } /// Clean up any resources being used. protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(YOURCLASSSCHEDULE)); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.linkLabel2 = new System.Windows.Forms.LinkLabel(); this.linkLabel3 = new System.Windows.Forms.LinkLabel(); this.linkLabel4 = new System.Windows.Forms.LinkLabel(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // linkLabel1 // this.linkLabel1.BackColor = System.Drawing.SystemColors.ActiveCaption; this.linkLabel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.linkLabel1.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 7); this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel1.Location = new System.Drawing.Point(41, 123); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(288, 32); this.linkLabel1.TabIndex = 1; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "Class 1"; this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // linkLabel2 // this.linkLabel2.BackColor = System.Drawing.SystemColors.ActiveCaption; this.linkLabel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.linkLabel2.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel2.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel2.Location = new System.Drawing.Point(467, 123); this.linkLabel2.Name = "linkLabel2"; this.linkLabel2.Size = new System.Drawing.Size(288, 32); this.linkLabel2.TabIndex = 2; this.linkLabel2.TabStop = true; this.linkLabel2.Text = "Class 2"; this.linkLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.linkLabel2.VisitedLinkColor = System.Drawing.Color.Navy; this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked); // // linkLabel3 // this.linkLabel3.BackColor = System.Drawing.SystemColors.ActiveCaption; this.linkLabel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.linkLabel3.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel3.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel3.Location = new System.Drawing.Point(41, 311); this.linkLabel3.Name = "linkLabel3"; this.linkLabel3.Size = new System.Drawing.Size(288, 32); this.linkLabel3.TabIndex = 3; this.linkLabel3.TabStop = true; this.linkLabel3.Text = "Class 3"; this.linkLabel3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked); // // linkLabel4 // this.linkLabel4.BackColor = System.Drawing.SystemColors.ActiveCaption; this.linkLabel4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.linkLabel4.Font = new System.Drawing.Font("Times New Roman", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.linkLabel4.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel4.Location = new System.Drawing.Point(467, 311); this.linkLabel4.Name = "linkLabel4"; this.linkLabel4.Size = new System.Drawing.Size(288, 32); this.linkLabel4.TabIndex = 4; this.linkLabel4.TabStop = true; this.linkLabel4.Text = "Class 4"; this.linkLabel4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked); // // button1 // this.button1.BackColor = System.Drawing.SystemColors.ActiveCaptionText; this.button1.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(64))))); this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button1.Font = new System.Drawing.Font("Pristina", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.ForeColor = System.Drawing.SystemColors.ActiveCaption; this.button1.ImageAlign = System.Drawing.ContentAlignment.TopCenter; this.button1.Location = new System.Drawing.Point(358, 206); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(101, 25); this.button1.TabIndex = 5; this.button1.Text = "Go Back"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // YOURCLASSSCHEDULE // this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(790, 482); this.Controls.Add(this.button1); this.Controls.Add(this.linkLabel4); this.Controls.Add(this.linkLabel3); this.Controls.Add(this.linkLabel2); this.Controls.Add(this.linkLabel1); this.Font = new System.Drawing.Font("OldDreadfulNo7 BT", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "YOURCLASSSCHEDULE"; this.Text = "Your Classes"; this.Load += new System.EventHandler(this.Form2_Load); this.ResumeLayout(false); } #endregion public void Form2_Load(object sender, System.EventArgs e) { // if (text == "900456317") // { //} } public void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/"); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/"); } private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/"); } private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.georgiasouthern.edu/map/"); } private void button1_Click(object sender, EventArgs e) { Form1 form1 = new Form1(); form1.Show(); this.Hide(); } } }

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >