Cannot invoke toString on the primitive type int

im trying to make a sudoku puzzle but having trouble with the arrays, ive got two arrays
int [][] actual = new int [9][9];
    String [][] possible = new String [9][9];part of my code im trying to generate a sudoku board, this is the part of the error in
public void possVals(int col, int row)
          if(possible[col][row].equals(""))
               str = "123456789";
          else str = possible[col][row];
          for(r = 1; r < 9; r++)
               if(actual[col][r] != 0)
                    str = str.Replace(actual[col][r].toString(), "");
          }could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' please

ajp_08 wrote:
could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' pleaseBut you can do like this
int i = 12345;
String s = Integer.toString(12345);So, the following should work
str = str.Replace(Integer.toString(actual[col][r]), "");Good luck!
Edited by: A.J.Bharanidharan on Nov 17, 2009 6:06 PM

Similar Messages

  • To get Class object representing the primitive type by a String

    for classes,I can use
    classNameString = "java.lang.String"
    Class c=Class.forName(classNameString);
    to get Class object representing the classNameString.
    but to get Class object representing the primitive type ,I have to use something like :
    Class c=Integer.TYPE;
    is there any way to get Class object representing the primitive type by a String?

    not using Class.forName(). you'll just need to key off the String passed to see whether it names a primitive:class ClassUtilities {
       * Gives the <code>Class</code> corresponding to a named class or primitive.
       * @param  name  FQN of a class, or the name of a primitive type
       * @param  loader  a {@link java.lang.ClassLoader ClassLoader}
       * @return  the <code>Class</code> for the name given.  This method
       * converts primitive type names to their particular <code>Class</code>
       * object.  <code>null</code>, the empty string, <code>"null"</code>, and
       * <code>"void"</code> yield {@link java.lang.Void#TYPE Void.TYPE}.  If any
       * classes require loading because of this operation, the given
       * <code>ClassLoader</code> performs the loading.  Such classes are not
       * initialized, however.
       * @throws  ClassNotFoundException  if the name names an unknown class
       * or primitive
       * @see  java.lang.Class#getName
      static Class classForNameOrPrimitive( String name, ClassLoader loader )
        throws ClassNotFoundException {
        if ( name == null || name.equals( "" ) || name.equals( "null" ) || name.equals( "void" ) ) {
          return Void.TYPE;
        if ( name.equals( "boolean" ) )
          return Boolean.TYPE;
        if ( name.equals( "byte" ) )
          return Byte.TYPE;
        if ( name.equals( "char" ) )
          return Character.TYPE;
        if ( name.equals( "double" ) )
          return Double.TYPE;
        if ( name.equals( "float" ) )
          return Float.TYPE;
        if ( name.equals( "int" ) )
          return Integer.TYPE;
        if ( name.equals( "long" ) )
          return Long.TYPE;
        if ( name.equals( "short" ) )
          return Short.TYPE;
        return Class.forName( name, false, loader );
    }

  • How to use the substring and can i class method for the primitive type

    MY COMPILER
    public class StringLine
    public static void main(String[] args)
    String sentence;
    char letter;
    char name;
    int position;
    System.out.println("Enter a line of text. No punctuation please");
    sentence = MyIO.readLine();
    System.out.println("I have rephrase that line to read:");
    position = sentence.indexOf(" ");
    name = sentence.charAt(postion, position+ 1);
    name = name.toUpperCase();
    letter = sentence.charAt(0);
    letter = letter.toLowerCase();
    sentence = name + sentence.substring(position + 2)
              + letter + sentence.substring(1, position);
    //////////////// I got 3 errors following:
    StringLine.java:16: cannot resolve symbol
    symbol : variable postion
    location: class StringLine
    name = sentence.charAt(postion, position+ 1);
    ^
    StringLine.java:17: char cannot be dereferenced
    name = name.toUpperCase();
    ^
    StringLine.java:20: char cannot be dereferenced
    letter = letter.toLowerCase();
    ^
    3 errors
    }

    position = sentence.indexOf(" ");
    name = sentence.charAt(postion, position+ 1);
    name = name.toUpperCase(); two error here:
    1. as stated above postion is mispelled...should be position
    2. you cannot perform a chatAT(int, int)
    I think you want to perform a substring
    String name;  // should be a string instead of a char..(char is a primitive and all primitive have no method)
    position = sentence.indexOf(" ");  
    name = sentence.substring(position, position + 1).toUpperCase();
    [./code]
    better yet..you should check if the sentence does contain a spaceString name;
    position = sentence.indexOf(" "); // return a negative value if the search string is not part of the string
    if (position != -1)
    name = sentence.substring(position, position + 1).toUpperCase();
    else
    System.out.println("The sentence does not contain a space);
    [./code]
    String letter;
    letter = new String(sentence.charAt(0));
    letter = letter.toLowerCase();
    // or
    char letter;
    letter = sentence.toLowercase().charAt(0);

  • Any Java built in function to get the Class type corresponding to primitive

    I know it sounds strange but basically I have a Class and a String (I'm reading values from an XML file).
    If the Class is a primitive type (boolean, byte, char, short, int, long, float, and double) I would have to convert the String into the corresponding types.
    So I know how to do stuff like
    Integer.parseInt("22");but for all the primitive types is there some method where I can simply get a way to do that without writing a whole bunch of if statements?

    You could set up a class to parse your String. You could check to see if it contains a decimal point, if so then you check to see if it is less than float.MAX_VALUE etc same for the Integer family and you could use equals method to check if it is true or false.
    one other way would be to use parseInt etc and catch exceptions if there is an error, this is a bad idea though and a dirty way to do things.
    As suggested, maybe you have some idea of what data type your expecting and can limit the amount of parsing you have to do. Another way is to group all numeric values as doubles.
    You could start with something like this adding other methods checking the max value of the data types.
    public class StringParser
         public static void main(String[] args)
              String test = "1.0";
              System.out.println(containsDecimal(test));
              if (containsDecimal(test))
                   decimalSizeFinder(test);
              else
                   integerSizeFinder(test);
         static boolean containsDecimal(String input)
              for(int i=0; i<input.length(); i++)
                   if (input.charAt(i) =='.')
                        return true;
              return false;
         static void integerSizeFinder(String input)
              long value = Long.parseLong(input);
              if(value <=Byte.MAX_VALUE)
                   byte b = (byte)value;
              else if(value <= Short.MAX_VALUE)
                   short s = (short)value;
              else if(value <=Integer.MAX_VALUE)
                    int i = (int)value;
              //etc
            //Add code to assign the value to a variable someplace
         static void decimalSizeFinder(String input)
              double value = Double.parseDouble(input);
              if(value <=Float.MAX_VALUE)
                   float f = (float)value;
           //Add code to assign the value to a variable someplace
    }Message was edited by:
    kikemelly
    Message was edited by:
    kikemelly

  • Getting the class of a primitive type or void

    Hello,
    Class.forName cannot be used to get the class of a primitive type or void. What does then ???
    I thought of defining a class for each primitive type and override getClass() to return the required type, but getClass() is final ...
    Please help

    I don't understand what you mean e.g.I get the name of the primitive type at runtime and need to convert it to a class. For example, Class.forName("byte") returns byte.class. But, unfortunately, Class.forName() doesn't return classes of primitives or void.
    I already solved the problem through putting ptimitive classes in a hashtable. But I was wondering if there is a simpler solution !!!

  • Need suggestion for variable size array of primitive type.

    Hi all,
    I am working on a problem in which I need to keep an array of primitive (type int) sorted. Also I insert new elements while keeping it sorted, and at times I merge two similar arrays with unique elements.
    I would welcome suggestions on the implementation aspects as to which type/class to use. My primary consideration is performance. Here are my observations:
    1. type int
    Efficient operation, but arrays are fixed size so it makes clumsy code and overhead when the array is expanded or merged with another.
    Methods in class Arrays can be used, incl. binary search and sort.
    2. Vector, ArrayList, List, LinkedList
    Accept objects only. I can use Integer instead of int, but it will involve overhead, and I'll need to write my own sort and search routines (already done).
    For now, I choose option 2 using Vectors. Is there a better choice, or are there other options, given the conditions and consideration enumerated at the beginning?
    Appreciate any input or comments.

    mathmate wrote:
    I have not had the occasion to use them in parallel to recognize the difference. It pays to talk to people!A small benchmark is easily constructed:
    import bak.pcj.list.IntArrayList;
    import java.util.Random;
    import java.util.ArrayList;
    public class CollectionTest {
        static void testObjectsList(ArrayList<Integer> list, int n, long seed) {
            long start = System.currentTimeMillis();
            Random rand = new Random(seed);
            for(int i = 0; i < n; i++)
                list.add(new Integer(rand.nextInt()));
            for(int i = 0; i < n/2; i++)
                list.remove(rand.nextInt(list.size()));
            long end = System.currentTimeMillis();
            System.out.println("objectsList -> "+(end-start)+" ms.");
        static void testPrimitiveList(IntArrayList list, int n, long seed) {
            long start = System.currentTimeMillis();
            Random rand = new Random(seed);
            for(int i = 0; i < n; i++)
                list.add(rand.nextInt());
            for(int i = 0; i < n/2; i++)
                list.remove(rand.nextInt(list.size()));
            long end = System.currentTimeMillis();
            System.out.println("primitiveList -> "+(end-start)+" ms.");
        public static void main(String[] args) {
            long seed = System.currentTimeMillis();
            int numTests = 100000;
            testObjectsList(new ArrayList<Integer>(), numTests, seed);
            testPrimitiveList(new IntArrayList(), numTests, seed);
    }In the test above, Java's ArrayList is about 5 times faster. But when commenting out the remove(...) methods, the primitive 3rd party IntArrayList is about 4 to 5 times faster.
    Give it a spin.
    Again: just try to do it with the standard classes: if performance lacks, look at something else.

  • Java.lang.IllegalArgumentException: Cannot invoke beans

    in 1 jsp page
    <logic:iterate id="msgg" name="messages">
    <tr>
    <td>${msgg.messageNumber}</td>
    <td>${msgg.from[0]}</td>
    ** <td><html:link action="msgbody?message=${msgg.message}">${msgg.subject}</html:link> </td>
    <td>${msgg.sentDate}</td>
    </tr>
    </logic:iterate>
    ${msgg.message} which will return javax.mail.Message object
    By clicking in the link(above shown as **) it will go to msgbody action and should set
    message property of bean with javax.mail.Message object
    for msg body action my bean is
    package beans;
    import javax.mail.Message;
    import org.apache.struts.action.ActionForm;
    public class MsgBn extends ActionForm {
    private Message message;
    public Message getMessage() {
    return message;
    public void setMessage(Message message) {
    this.message = message;
    i am getting following exception plz suggest me solutions
    java.lang.IllegalArgumentException: Cannot invoke beans.MsgBn.setMessage - argument type mismatch
    org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:1778)
    org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1759)
    org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
    org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
    org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)
    org.apache.commons.beanutils.BeanUtilsBean.populate(BeanUtilsBean.java:811)
    org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:298)
    org.apache.struts.util.RequestUtils.populate(RequestUtils.java:493)

    Of course it's a String. It's being passed as a request parameter. Request parameters are always Strings.
    It looks like something needs to be held in the session maybe?

  • How to determine the object type?

    Hi,
    I got a method that is of the following signature:
    Object result = method.invoke(object,args);The result can be any type from primitive types like double to class type.
    How can I determine whether the result object is of what type?
    I am thinking of using
    (if result instanceof Double)
          //do something
    }However, the method call invoke can return a primitive type double, so will the above method
    (if result instanceodf Double) be called?
    Thanks.

    However, the method call invoke can return a primitive
    type double, so will the above method
    (if result instanceodf Double) be called?(result instanceof Double) will be true because quoting the javadocs for Method.invoke(): "if the value has a primitive type, it is first appropriately wrapped in an object."
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object[])

  • How to get the data type of a column?

    I plan to construct a dynamic insert statement, so the column's type is needed, any possible to get what type of a column within mysql's table?
    Message was edited by:
    ioiioi

    Think about it this way
    You can find out the type of the columns but can you convert the data items that you have to insert in to the table in to the proper column type. And you will also have to write a long if-else-if if you try to do this.
    Just make the JDBC driver worry about this.
    Try something like this.
    public void insert(String table, Object data[]){
       //You should write the getNumCollumns method
       //to return the number of columns in the table
       // Using Matadata Objects
       int noOfColumns = getNumCollumns(table);
       if (noOfColumns  != data.length)
          throw new IncorrectNumberOfValuesException();
       //You should write this exception probably to be a subclass of SQLException
       //Now construct the insert statement
       StringBuffer sb = new StringBuffer("INSERT INTO ");
       sb.append(table);
       sb.append(" VALUES (");
       for (int i=0; i<noOfColumns ; i++){
          sb.append("?");
          if (i< (noOfColumns-1))
             sb.append(",");
       sb.append(")");
      //If you want you can cache the statement againt the table name
      //Now create your prepared statement
      PreparedStatement ps = connection.prepareStatement(sb.toString());
      //Set the data
      for (int i=0; i<data.length; i++){
          ps.setObject(i+1, data);
    //Execute
    ps.executeUpdate();
    ps.close();
    In the above code the caller is responsible for sending the data with proper java type to be inserted and the driver will do the conversion. I have used this approach in a project few years ago and I havent got any complains.
    WARNING: I havent compiled above code. It may have typos

  • Hash tables in combination with data references to the line type.

    I'm having an issue with hash tables - in combination with reference variables.
    Consider the following:  (Which is part of a class)  -  it attempts to see if a particular id exists in a table; if not add it; if yes change it.   
      types: BEGIN OF TY_MEASUREMENT,
               perfid      TYPE zgz_perf_metric_id,
               rtime       TYPE zgz_perf_runtime,
               execount    TYPE zgz_perf_execount,
               last_start  TYPE timestampl,
             END OF TY_MEASUREMENT.
    METHOD START.
      DATA:  ls_measurement TYPE REF TO ty_measurement.
      READ TABLE gt_measurements WITH TABLE KEY perfid = i_perfid reference into ls_measurement.
      if sy-subrc <> 0.
        "Didn't find it.
        create data ls_measurement.
        ls_measurement->perfid = i_perfid.
        insert ls_measurement->* into gt_measurements.
      endif.
      GET TIME STAMP FIELD ls_measurements-last_start.
      ls_measurement->execount = ls_measurement->execount + 1.
    ENDMETHOD.
    I get compile errors on the insert statement - either "You cannot use explicit index operations on tables with types HASHED TABLE" or "ANY TABLE".      It is possible that.
    If I don't dereference the type then I get the error  LS_MEASUREMENT cannot be converted to the line type of GT_MEASUREMENTS.
    I'm not looking to solve this with a combination of references and work ares - want a reference solution.   
    Thanks!
    _Ryan
    Moderator message - Moved to the correct forum
    Edited by: Rob Burbank on Apr 22, 2010 4:43 PM

    I think it might work when you change it for
    insert ls_measurement->* into TABLE gt_measurements.
    For hashed table a new line here will be inserted according to given table key.
    Regards
    Marcin

  • Error in CLR: InvalidOperationException - The current type is an interface and cannot be constructed. Are you missing a type mapping?

    Hi, I'm trying to execute a .NET assembly's method from SQL Server 2012 Express, but I'm stuck with this error calling the sp:
    Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type ISymmetricCryptoProvider, key "TripleDESCryptoServiceProvider" ---> Microsoft.Practices.Unity.ResolutionFailedException:
    Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.ISymmetricCryptoProvider", name = "TripleDESCryptoServiceProvider".
    Exception occurred while: while resolving.
    Exception is: InvalidOperationException - The current type, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.ISymmetricCryptoProvider, is an interface and cannot be constructed. Are you missing a type mapping?
    At the time of the exception, the container was:
      Resolving Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.ISymmetricCryptoProvider,TripleDESCryptoServiceProvider
     ---> System.InvalidOperationException: The current type, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.ISymmetricCryptoProvider, is an interface and cannot be constructed. Are you missing a type mapping?
    System.InvalidOperationException:
       en Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
       en BuildUp_Microsoft.Practices.EnterpriseLibrary.Security
    Microsoft.Practices.ServiceLocation.ActivationException:
       en Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
       en Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService](String key)
       en Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Cryptographer.GetSymmetricCryptoProvider(String symmetricInstance)
       en Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Cryptographer.DecryptSymmetric(String symmetricInstance, String ciphertextBase64)
       en ...
    Is there any limitation by design for Interface instantiation from CLR database?
    Any help I will appreciate, thanks a million!!

    Bob, thanks for your response.. Yes, the code works fine outside of SQLCLR. This is the class I'm trying to instantiate, I'm using it to envolve Cryptographer, an Enterprise Library 5.0 class actually, so I have no control to test it without referring the
    interface.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
    using System.Security.Cryptography;
    using Microsoft.SqlServer.Server;
    using System.Data.SqlTypes;
    namespace Cars.UtileriasGlobales.Helpers
        /// <summary>
        /// Clase que permite encriptar y desencriptar cadenas de textos utilizando
        /// TripleDESCryptoServiceProvider de Enterprise Library 5.0
        /// </summary>
        public static class Cryptography
            #region Metodos
            [SqlProcedure]
            public static void DesencriptarSQLServer(SqlString cadena, out SqlString cadenaDesencriptada)
                cadenaDesencriptada = !String.IsNullOrEmpty(cadena.ToString()) ? Cryptographer.DecryptSymmetric("TripleDESCryptoServiceProvider", cadena.ToString().Replace(" ", "+"))
    : String.Empty;
            #endregion
    I have collected all the dependent assemblies in one directory 'C:\migrate', so the create assembly finish ok. This is the script to create the assembly I'm using:
    sp_configure 'clr enable', 1
    GO
    RECONFIGURE
    GO
    ALTER DATABASE cars SET TRUSTWORTHY ON
    GO
    CREATE ASSEMBLY CryptographyEntLib5
    AUTHORIZATION dbo
    FROM 'C:\migrate\Cars.UtileriasGlobales.dll'
    WITH PERMISSION_SET = UNSAFE
    GO
    CREATE PROCEDURE usp_Desencriptar
    @cadena nvarchar(200),
    @cadenaDesencriptada nvarchar(MAX) OUTPUT
    AS EXTERNAL NAME CryptographyEntLib5.[Cars.UtileriasGlobales.Helpers.Cryptography].DesencriptarSQLServer
    GO
    DECLARE @msg nvarchar(MAX)
    EXEC usp_Desencriptar 'Kittu And Tannu',@msg output
    PRINT @msg

  • Cannot invoke method "setMessageListener" within the J2EE container.

    I use TopicSubscriber.setMessageListener method to convert messages to my own type, but oc4j jms throws following exception:
    javax.jms.JMSException: TopicSubscriber[Oc4jJMS.Consumer.ypchang-cn.12da4a6:111d4f12137:-8000.94,Topic[CreatedSponsorTopic],null,null,false]: cannot invoke method "setMessageListener" within the J2EE container.
         at com.evermind.server.jms.JMSUtils.make(JMSUtils.java:1072)
         at com.evermind.server.jms.JMSUtils.toJMSException(JMSUtils.java:1152)
         at com.evermind.server.jms.JMSUtils.toJMSException(JMSUtils.java:1123)
         at com.evermind.server.jms.JMSUtils.assertNotContainer(JMSUtils.java:1538)
         at com.evermind.server.jms.EvermindMessageConsumer.setMessageListener(EvermindMessageConsumer.java:217)
         at com.firepond.bcmf.bus.BusSubscriberImpl.setMessageListener(BusSubscriberImpl.java:397)
    OC4J JMS doesn't support user defined MessageListener?????!!!!!!!!!!
    Who can help me out?
    Thanks!

    Hi,
    I am facing the same problem did you got any solution for it.
    I am getting the following error message too:
    Exception in Constructor
    javax.jms.JMSException: QueueReceiver[Oc4jJMS.Consumer.ssipl-wrkst-139.-7dd2dd24:1122873d95f:-8000.269,Queue[360Transaction]]: cannot invoke method "setMessageListener" within the J2EE container.
         at com.evermind.server.jms.JMSUtils.make(JMSUtils.java:1072)
         at com.evermind.server.jms.JMSUtils.toJMSException(JMSUtils.java:1152)
         at com.evermind.server.jms.JMSUtils.toJMSException(JMSUtils.java:1123)
         at com.evermind.server.jms.JMSUtils.assertNotContainer(JMSUtils.java:1538)
         at com.evermind.server.jms.EvermindMessageConsumer.setMessageListener(EvermindMessageConsumer.java:217)
         at com.skillnetinc.storehub.connector.pos.publisher.ejb.publishTransactionWithSalesAudit.PublishTransactionWithSalesAuditBean.<init>(PublishTransactionWithSalesAuditBean.java:94)
         at PublishTransactionWithSalesAuditBean_RemoteProxy_1dpbn83.OC4J_createBeanInstance(Unknown Source)
         at com.evermind.server.ejb.StatelessSessionBeanPool.createContextImpl(StatelessSessionBeanPool.java:37)
         at com.evermind.server.ejb.BeanPool.createContext(BeanPool.java:418)
         at com.evermind.server.ejb.BeanPool.allocateContext(BeanPool.java:244)
         at com.evermind.server.ejb.StatelessSessionEJBHome.getContextInstance(StatelessSessionEJBHome.java:25)
         at com.evermind.server.ejb.StatelessSessionEJBObject.OC4J_invokeMethod(StatelessSessionEJBObject.java:86)
         at PublishTransactionWithSalesAuditBean_RemoteProxy_1dpbn83.invoke(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.evermind.server.rmi.RmiMethodCall.run(RmiMethodCall.java:53)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:595)

  • Operator + cannot be applied to operands of type 'method group and 'int'

    Hello I have a problem that I'm trying to fire a bullet everytime I pressed the spacebar key, but I have this problem that is cropping up.
     if ((e.KeyCode == Keys.Space) && (playerOne.Bullet.Alive == false))
                                playerOne.Bullet.Alive = true;
                                playerOne.Bullet.getX = playerOne.getXposition + 15;
                                playerOne.Bullet.getY = playerOne.getYposition + 10;
    It says in the error list: "Opeartor '+' cannot be applied to operands of type 'method group' and 'int'", I have no clue. I'm also new to programming.

    I want to get the bullet to shoot where the player is, here is the code:
    class Player
            // attributes here  -   Int other words data types and variables:
            int health = 3;
            float xPosition;
            float yPosition;
            Bitmap playerGraphics;
            int score = 0;
            bool leftPressed;
            bool rightPressed;
            float Width = 50;
            public Bullet Bullet = new Bullet();
            // functions here:
            public void Init()
                // Get Player_Bat.png from resources, so that we can work with it:
                playerGraphics = new Bitmap(Green_Aliens.Properties.Resources.Player_Bat);
                health = 3;
                score = 0;
                xPosition = 375;
                yPosition = 540;
                leftPressed = false;
                rightPressed = false;
                Bullet Bullet = new Bullet();
            public float getWidth()
                return Width;
            public void toggleLeftPressed()
                if (leftPressed == true)
                    leftPressed = false;
                else
                    leftPressed = true;
            public void toggleRightPressed()
                if (rightPressed == true)
                    rightPressed = false;
                else
                    rightPressed = true;
            public bool getLeftPressed()
                return leftPressed;
            public bool getRightpressed()
                return rightPressed;
            public Bitmap getGraphics()
                return playerGraphics;
            public float getXposition()
                return xPosition;
            public float getYposition()
                return yPosition;
            public int getHealth()
                return health;
            public int getScore()
                return score;
            public void moveLeft()
                xPosition -= 10;
            public void moveRight()
                xPosition += 10;
            public void loseLife()
                health--;
            public void adScore(int valueAdd)
                score += valueAdd;
            //Resets the player to the start position:
            public void resetPosition()
                xPosition = 400;
                yPosition = 550;

  • Conversion failed when converting the nvarchar value to data type int when returning nvarchar(max) from stored procedure

    Thank you for your help!!! 
    I've created a stored procedure to return results as xml.  I'm having trouble figuring out why I'm getting the error message "Conversion failed when converting the nvarchar value '<tr>.....'
    to data type int.    It seems like the system doesn't know that I'm returning a string... Or, I'm doing something that I just don't see.
    ALTER PROCEDURE [dbo].[p_getTestResults]
    @xml NVARCHAR(MAX) OUTPUT
    AS
    BEGIN
    CREATE TABLE #Temp
    [TestNameId] int,
    [MaxTestDate] [DateTime],
    [Name] [nvarchar](50),
    [Duration] [varchar](10)
    DECLARE @body NVARCHAR(MAX)
    ;WITH T1 AS
    SELECT DISTINCT
    Test.TestNameId
    , replace(str(Test.TotalTime/3600,len(ltrim(Test.TotalTime/3600))+abs(sign(Test.TotalTime/359999)-1)) + ':' + str((Test.TotalTime/60)%60,2)+':' + str(Test.TotalTime%60,2),' ','0') as Duration
    ,MaxTestDate = MAX(TestDate) OVER (PARTITION BY TM.TestNameId)
    ,TestDate
    ,TM.Name
    ,Test.TotalTime
    ,RowId = ROW_NUMBER() OVER
    PARTITION BY
    TM.TestNameId
    ORDER BY
    TestDate DESC
    FROM
    Test
    inner join TestName TM on Test.TestNameID = TM.TestNameID
    where not Test.TestNameID in (24,25,26,27)
    INSERT INTO #Temp
    SELECT
    T1.TestNameId
    ,T1.MaxTestDate
    ,T1.[Name]
    ,T1.Duration
    FROM
    T1
    WHERE
    T1.RowId = 1
    ORDER BY
    T1.TestNameId
    SET @body ='<html><body><H3>TEST RESULTS INFO</H3>
    <table border = 1>
    <tr>
    <th> TestNameId </th> <th> MaxTestDate </th> <th> Name </th> <th> Duration </th></tr>'
    SET @xml = CAST((
    SELECT CAST(TestNameId AS NVARCHAR(4)) as 'td'
    , CAST([MaxTestDate] AS NVARCHAR(11)) AS 'td'
    , [Name] AS 'td'
    , CAST([Duration] AS NVARCHAR(10)) AS 'td'
    FROM #Temp
    ORDER BY TestNameId
    FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
    SET @body = @body + @xml +'</table></body></html>'
    DROP TABLE #Temp
    RETURN @xml
    END
    closl

    Your dont need RETURN inside SP as you've declared @xml already as an OUTPUT parameter. Also you can RETURN only integer values using RETURN statement inside stored procedure as that's default return type of SP.
    so just remove RETURN statement and it would work fine
    To retrieve value outside you need to invoke it as below
    DECLARE @ret nvarchar(max)
    EXEC dbo.[P_gettestresults] @ret OUT
    SELECT @ret
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How can I invoke a method on a subclass based on the runtime type?

    Hi all,
    I have defined a base class OrderDetail, and 2 subclasses which extend it: OrderDetailSingleReservation and OrderDetailMonthReservation. Furthermore, I have a method:
        public Order order_generate(OrderDetail orderDetail) {
            if (orderDetail instanceof OrderDetailSingleReservation) {
                return order_generate((OrderDetailSingleReservation) orderDetail);
            }  else if (orderDetail instanceof OrderDetailMonthReservation) {
                return order_generate((OrderDetailMonthReservation) orderDetail);
            } else {
                Misc.alert("orderAndInvoice_Generate(GENERIC): unsupported type.");
                return null;
        }The type of this method's parameter is OrderDetail, as you can see. (This particular method only serves as a kind of dispatcher and is therefore not very interesting in itself, but the same pattern using 'instanceof' occurs in a codebase I am working on several times, and I would like to factor it out if possible.)
    My question: it seems that the invocation of order_generate() from within this method requires an explicit downcast to one of the two subclasses. If not, java invokes the method on the superclass. But at runtime, the JVM knows what type of object it is dealing with, right? So is there no way to do this without the explicit downcast?
    A similar problem occurs when trying to invoke a method on an object whose type is one of the subclasses; the method on superclass is called, instead of the one in the appropriate subclass that overrides it.
    Any help would be greatly appreciated!
    Thanks,
    Erik

    Thanks for your replies! I was editing my post last night to clarify it, but my connection went down and the edit was lost :(
    Anyway, yes, it should be done with polymorphism. I was constructing an example using the famous Animal, Cat and Dog classes to demonstrate my question more clearly, and to my surprise the problem does not occur in my example code.
    LRMK: Invoking a method such as in your example, where the method is inside the class itself, works fine. However for MVC's sake, I have a separate class called Invoicing with methods as below:
    class invoicing
      // the method for the superclass
      public Invoice invoice_create(OrderDetail orderDetail) {
         System.out.println("type: " + orderDetail.getClass());
         return null;
      // the method for one of the subclasses (this method is being not invoked)
      public Invoice invoice_create(OrderDetailSingleReservation orderDetail) {
         return null;
      // ...nor is this one.
      public Invoice invoice_create(OrderDetailMonthReservation od) {
         return null;
    }Now I attempt to invoke these methods:
    // create example objects
    OrderDetailSingleReservation odSingle = new OrderDetailSingleReservation();
    OrderDetailMonthReservation odMonth = new OrderDetailMonthReservation();
    // this call displays "odSingle type: OrderDetailSingleReservation"
    System.out.println("odSingle type: " + odSingle.getClass());
    // this call displays "odMonth type: OrderDetailMonthReservation"
    System.out.println("odMonth type: " + odMonth.getClass());
    // this call invokes Invoicing.invoice_create(OrderDetail)
    // instead of Invoicing.invoice_create(OrderDetailSingleReservation)
    Invoicing.invoice_create(odSingle);
    // this call invokes Invoicing.invoice_create(OrderDetail)
    // instead of Invoicing.invoice_create(OrderDetailMonthReservation)
    Invoicing.invoice_create(odMonth);So these calls will invoke the method for the superclass, i.e. Invoicing.invoice_create(OrderDetail od). That method then then executes the System.out.println() call which displays the class type of its parameter as one of { OrderDetailSingleReservation | OrderDetailMonthReservation }, that is, the expected subclass types!
    So the dynamic dispatch isn't working the way I would expect it to. If I do the explicit if-else checking using instanceof, as described in my first post, the correct methods are called.
    I hope the problem is somewhat clearer now. I am a bit lost as to what might be causing this, or how to monitor what's going on inside the jvm. Any ideas? BTW, the OrderDetail class and its subclasses are JPA entities (though I don't think it should matter).
    Thanks!
    Erik

Maybe you are looking for

  • Error while trying to access repository from Application Explorer

    Hi All, I am trying to access the targets which I had previously created from AE. Everything was working fine. When I tried running iwae.sh script and open the target from AE it throws below error today. com.iwaysoftware.iwrepository.RepositoryExcept

  • Question on Persistence (Entity Beans, Hibernate, JDBC)

    Hi everybody! Until now, I have read a lot about persistence in the J2EE-sector, but I am still confused about which technology to used in my case. I hope, that maybe you can give me some hints, by telling me which technology is good or bad regarding

  • Setting headers to the HttpRequest

    How to set content in header of the ServletRequest.. Can any body please help me ..

  • Mail stopped querying other email address'

    without having changed anything (that I know of) my mail program suddenly stopped querying my home email server. I travel often between two states and have two internet companies and two email addresses which both always send email to my mac mail pro

  • Createpdf desktop printer problem

        Is there a trick to getting createpdf desktop printer to work? For some reason I see documents in the printer queue with an error message but I can't figure out how to fix the problem.