Comparing a class with Class-Object

Hi there:
I receive a Class-Object and have to compare it
with a class, for example:
public boolean stringClass(Class cl) {
  if (cl.equals("".getClass))
    return true;
  else
    return false;
}I don't like this because in case of complex objects I have
to create this object only for comparing, it's very inefficient:
public boolean specialClass(Class cl)
   return cl.equals((new Special(<many parameters .. >)).getClass());
}Any idea? Am I simply confused to see a clear solution?
I will prefer something like this:
if ( cl == Special.getClass())Thanx
Andreas

If you have an object, for example a String object, then you can check if this object is really a String:
Object o = new String("");
if (o instanceof String) {
  System.out.println("The object is a String");
}Can you use that, or do you really want to test if a Class object is the name of a given class?
Class cl = String.class;
if (cl.getName().equals("java.lang.String")) {
  System.out.println("String Class");
}

Similar Messages

  • Re: How to create More two class with one object

    haii,
             i have small information How to create More two class with one object,
    bye
    bye
    babu

    Hello
    I assume you want to create multiple instance of your class.
    Assuming that you class is NOT a singleton then simply repeat the CREATE OBJECT statement as many times as you need.
    TYPES: begin of ty_s_class.
    TYPES: instance   TYPE REF TO zcl_myclass.
    TYPES: end of ty_s_class.
    DATA:
      lt_itab      TYPE STANDARD TABLE OF ty_s_class
                     WITH DEFAULT KEY,
      ls_record  TYPE ty_s_class.
      DO 10 TIMES.
        CLEAR: ls_record-instance.
        CREATE OBJECT ls_record-instance.
        APPEND ls_record TO lt_itab.
      ENDDO.
    Regards
      Uwe

  • How to compile a java file to class with class

    There is a java file.
    And i want to compile it with class, not javac command.
    so i can catch the compile errors.
    how to do it?
    special thanks.

    http://java.sun.com/developer/JDCTechTips/2003/tt0722.html#2

  • Can't load class with Class.forName()

    Hi, can somebody help me with this problem. I have clas copiled with jdk 1.3.1 (I also test it with jdk 1.4.1). If I try to load a Class instance with Class.forName("package.app.MyClass)") I have a runtime exception:
    java.lang.ClassNotFoundException: com.unisys.ebs.all.ispecs.GD130IspecModel
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:183)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:294)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:310)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:115)
         at com.unisys.util.ObjectLoader.load(ObjectLoader.java:60)
         at com.unisys.jellybeans.IspecFactory.getIspec(IspecFactory.java:74)
         at com.unisys.jellybeans.LINCEnvironment.getIspec(LINCEnvironment.java:1012)
         at com.unisys.ebs.middleware.TestLinc.initConnection(TestLinc.java:52)
         at com.unisys.ebs.middleware.TestLinc.main(TestLinc.java:106)
    but if instead of this I instantiate the class calling the constructor and writing an import sentence, it works fine. I really need to instantiate this class via Class.forName because it extends a superclass and know the class to instantiate only at runtime. I will appreciate any help. Thanks.
    Pablo Antonioletti

    I removed the import in the file header and wrote this code:
    try{           
    ispecModel = new com.unisys.ebs.all.ispecs.GD130IspecModel();
    Class ispecClass = Class.forName("com.unisys.ebs.all.ispecs.GD130IspecModel.class");
    catch(Exception e)
    e.printStackTrace();
    the new sentence work fine, if write mor code I can access methods and members. When the runtime execute the Class.forName sentence the exception is thrown. I put all in the same file and class to avoid mistakes typing class path.
    This is very rare I never seen it before and I developed java application since five years ago.

  • Restrict 1 Charachteristic per class in assigned object

    Hi Gurus,
    I am using clasification system for reporting in vendors. I have created a class with class type 010 and assigned charachterictics to the class. When I assign this class to the object, i.e Vendor. I want the asignment of charachteristic value to be restricted one charachteristic and one value therein.
    I want to assign just one value of a characteristic, the we sholud be ablle to assin multiple charachterisitc pertaining to a specifc class. The end result should one valu from any one of the charachterisic of a specific class.
    Thanks and Regards,
    Abdul Kadir Rajbhoy

    Create multiple class with class type 010 and assign only one characteristics for each of the class.
    e.g:
    Class: CL1 - Assign Characteristics CHAR1
    Class: CL2 - Assign Characteristics CHAR2
    Class: CL3 - Assign Characteristics CHAR3
    Class: CL4 - Assign Characteristics CHAR3
    In the vendor class assignment, chhose one of the class and assign values to the characteristics.

  • Having problems in creating a class with name File.

    I want to compile a new class with class name as File, i have made it part of a new package also but still i am getting this error
    "File.java:2: CustomFile.File is already defined in this compilation unit
    import java.io.File;
    ^
    File.java:6: cannot resolve symbol
    symbol : constructor File ()
    location: class java.io.File
    inFile = new java.io.File();
    ^
    2 errors"
    Here is the source code of the file:
    package CustomFile;
    import java.io.File;
    public class File {
    private java.io.File inFile;
    public File(){
         inFile = new java.io.File();
         System.out.println("hi file");
    }

    Any help is appreciated.
    I want to compile a new class with class name as File,
    i have made it part of a new package also but still i
    am getting this error
    "File.java:2: CustomFile.File is already defined in
    this compilation unit
    import java.io.File;
    ^
    File.java:6: cannot resolve symbol
    symbol : constructor File ()
    location: class java.io.File
    inFile = new java.io.File();
    ^
    2 errors"
    Here is the source code of the file:
    package CustomFile;
    import java.io.File;
    public class File {
    private java.io.File inFile;
    public File(){
         inFile = new java.io.File();
         System.out.println("hi file");

  • Gen. List of a gen. class with a gen. type of a Comparable ? super C

    Hi,
    I'm facing a (little ;-)) problem getting my code free of unchecked warnings.
    Please consider the following code:
    There are two generic classes:
    public class AppDbObjectCache<T extends AppDbObject> {
      private List<AppDbObjectCacheIndex<T,?>> indexes;
      // select an object via cache by unique key
      public <C extends Comparable<? super C>> T select(int handle,  C key)  {
        // unchecked warning (won't compile without cast)
        AppDbObjectCacheIndex<T,C> index = (AppDbObjectCacheIndex<T,C>)indexes.get(handle);
    }and:
    public class AppDbObjectCacheIndex<T extends AppDbObject, C extends Comparable<? super C>> {
    }My problem is the wildcard in private List<AppDbObjectCacheIndex<T,?>> indexes
    because I need a cast whenever I get an element out of the List and
    that cast triggers an unchecked warning.
    I tried:
    private List<AppDbObjectCacheIndex<T,? extends Comparable<?>>> indexes;but the compiler is right about the fact that a Comparable<?> is
    not the same as a C extends Comparable<? super C> and still
    insists on a cast.
    Then I tried:
    private List<AppDbObjectCacheIndex<T,? extends Comparable<? extends ?>>>which is nonsense, of course, but it shows the problem of having two
    different wildcards and I have no clue how to express that.
    To introduce the second wildcard, i.e. the 'C', I tried:
    private <C extends Comparable<? super C>> List<AppDbObjectCacheIndex<T,C> indexes;but the compiler complains about a wrong syntax, because declaring
    a generic type is only allowed for classes and methods and not for
    variable declarations.
    Is there a way to express in the List-declaration that the 2nd type
    variable of the List's objects is something that extends a Comparable of a superclass of itself?
    Or do I have to live with the casts as with Class.forName() ?
    Any idea?
    Thanx,
    Harald

    Ok.
    Here is an example stripped down to the very essentials.
    We're talking about a typesafe generic cache for persistable objects
    (stored in a database in real life, but that doesn't matter in this example).
    There are 5 classes:
    - the superclass for all such objects. These objects are uniquely
    identified by a Long integer, the so-called object-id.
    - the sample object class to be cached. Instances of this class are
    additionally unique by their name, which is a String.
    - the sample class showing how to setup and use the cache.
    - the generic cache with the ability for managing any number of unique indexes
    - the generic cache index
    So far, so good.
    The super class of all database objects:
    * database object
    public class BlaObject {
      private long id;        // unique object id
      public void setId(long id) {
        this.id = id;
      public long getId() {
        return id;
      public BlaObject getFromStorageById(long id)  {
        // whatever is necessary to get it from storage by id ...
        return this;
    }The sample object class extended by the unique attribute 'name':
    public class BlaExampleObject extends BlaObject {
      private String name;    // unique name
      public void setName(String name)  {
        this.name = name;
      public String getName() {
        return name;
      public BlaExampleObject getFromStorageById(long id)  {
        return (BlaExampleObject)super.getFromStorageById(id);
      public BlaExampleObject getFromStorageByName(String name)  {
        // whatever is necessary to get it from storage by name ...
        return this;
    }The example how to use the cache:
    public class BlaCacheExample {
      public BlaCacheExample()  {
        BlaObjectCache<BlaExampleObject> cache = new BlaObjectCache<BlaExampleObject>();
        // create first index by object-id
        int idHandle = cache.addIndex(new BlaObjectCacheIndex<BlaExampleObject,Long>() {
          public BlaExampleObject select(Long id) {
            return new BlaExampleObject().getFromStorageById(id);
          public Long extract(BlaExampleObject object) {
            return object.getId();
        // create second index by name
        int nameHandle = cache.addIndex(new BlaObjectCacheIndex<BlaExampleObject,String>() {
          public BlaExampleObject select(String name) {
            return new BlaExampleObject().getFromStorageByName(name);
          public String extract(BlaExampleObject object) {
            return object.getName();
        // get an object by id via cache
        BlaExampleObject object = cache.select(idHandle, new Long(1234));
        // get it via name
        object = cache.select(nameHandle, "test");
    }The cache:
    import java.util.*;
    * Object cache with multiple unique indexes.
    public class BlaObjectCache<T extends BlaObject> {
      // >>>>> WHAT IS THE CORRECT DECLARATION FOR '?'  <<<<< ??????????????????
      private List<BlaObjectCacheIndex<T,?>> indexes;   // the indexes
       * creates an instance of an BlaObjectCache.
      public BlaObjectCache() {
        indexes = new ArrayList<BlaObjectCacheIndex<T,?>>();
       * add a unique index
       * @param index is the index to add
       * @return the handle to the index
      public <C extends Comparable<? super C>> int addIndex(BlaObjectCacheIndex<T,C> index)  {
        indexes.add(index);
        return indexes.size() - 1;
       * Retrieve object via cache
       * @param handle is the index-handle
       * @param key is unique key
       * @return the object or null if no such object
      public <C extends Comparable<? super C>> T select(int handle, C key)  {
          BlaObjectCacheIndex<T,C> index = (BlaObjectCacheIndex<T,C>)indexes.get(handle);
          T obj = index.get(key);   // get object from cache
          if (obj == null)  {
            // not in cache: get it from storage
            obj = index.select(key);
            if (obj != null)  {
              // add object to all indexes
              for (BlaObjectCacheIndex<T,?> ndx: indexes)  {
                ndx.add(obj);
          return obj;
    }and the cache index:
    import java.util.*;
    * Generic Cache index.
    public abstract class BlaObjectCacheIndex<T extends BlaObject, C extends Comparable<? super C>> {
      private TreeMap<C, T> cacheMap;     // mapping of keys to BlaObjects
       * Create a new index.
      public BlaObjectCacheIndex()  {
        cacheMap = new TreeMap<C, T>();
       * Select a BlaObject by a unique key from storage.
       * @param key uniquely identifies the object
       * @return the selected object or null if it does not exist.
      abstract public T select(C key);
       * Extract the key object.
       * @param object is the object to extract the key from
       * @return the key
      abstract public C extract(T object);
       * get object from cache by key.
       * @param key is the Comparable that uniquely identifies the object
       * @return the object or null if not in cache
      public T get(C key)  {
        return cacheMap.get(key);
       * add an object to the index.
       * @param object is the object to append
       * @return true if added, false if object already in index
      public boolean add(T object) {
        return cacheMap.put(extract(object), object) == null;  
    }The BlaObjectCacheIndex is 100% generic and typesafe.
    The problem arises in BlaObjectCache because it contains a
    List of BlaObjectCacheIndexes with different <C extends Comparable<? super C>>.
    Hence, I cannot make C a generic type variable
    for BlaObjectCache. However, I can force type checking for 'C' in
    the method-declarations of BlaObjectCache.
    Unfortunately, there is no way to describe
    that this List contains such elements. At least, I couldn't figure out
    how, so far :-(
    My reasoning is: there is no nasty type-casting or whatever trick in BlaObjectCacheIndex.
    The type-constraints correspond to the real demands of the application.
    A generic type like <C extends Comparable<? super C>> is not rocket science ;-)
    I just want to learn how to get the List-declaration right.
    Can you explain how?
    Regards,
    Harald

  • Class with objects compile error in Java 1.5.0 and 1.4.2.05

    Hi, I have some problems with creating objects to my java program.
    See below:
    JAVA, creating new class object.
    class AccountTest {
         public static void main(String[]args) {
         Account olesAccount = new Account(123456676756L, "Ole Olsen", 2300.50);
         olesAccount.deposit(1000.0); //Input of 1000$ to account
         double balance = olesAccount.findBalance(); //Ask object about balance!
         System.out.println("Balance: " +balance);
    ERRORS, from compiler (javac):
    AccountTest.java:7: cannot find symbol
    symbol : class Account
    location: class AccountTest
    Account olesAccount = new Account(123456676756L, "Ole Olsen", 2300.50);
    ^
    AccountTest.java:7: cannot find symbol
    symbol : class Account
    location: class AccountTest
    Account olesAccount = new Account(123456676756L, "Ole Olsen", 2300.50);
    ^
    2 errors
    This error occurs with both java 1.5.0 RC and 1.4.2.05
    */

    Assuming you haven't forgotten to compile the Account class, tt seems to be a problem with visibility. Are you sure your classpath is set up correctly and that the class Account is visible to the AccountTest driver?
    I'd try moving the Account out of whatever package it's in right now and making it public. Then, restrict acces from there.

  • I can load an Applet .class file with an OBJECT tag...

    How can I load a .jar file? I foolishly believed I could replace "myclass.class" with "myjar.jar" in the <PARAM> tag associated with an <OBJECT> tag, and if I had created my manifest file correctly, the Main-Class in my .jar would have its init() method called upon IE load of the web-page. But alas, it is not that simple.
    Is there an incantation of the <OBJECT> tag that is appropriate for .jar files?
    Thanks in advance for any help you can provide in this area.

    Please ignore the duplication. My browser burped, and I can't seem to figure out how to delete a thread.
    See answer posted in other thread.

  • BOXIR2: Object name not prefixed with class

    While creating Webintelligence report from a universe having more than one Dimension object with same name in different classes, the Object name is not prefixed with Class Name.
    1. The issue occurs after migration to XIR2 Webintelligence.
    2. 6.5 version of WebIntelligence and XI Desktop intelligence is prefixing class name in above scenario.
    REPRODUCTION STEPS:
    Create a universe with 2 classes (C1 & C2), Create a dimension object D1, D2 under class C1 and D2 & D3 under class C2. Export the universe.
    Create a webi report from the published universe, In Java Query panel , Drag all 4 Dimension Objects to Query Filter Section.
    Perform the above in Webintelligence of BO 6.5 & BO XI. Note that in BOXI Class name is not prefixed.
    Please let me know weather its change in the product or bug.

    Yes this is a bug...

  • Need help with generic class with comparable type

    Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
    I cant get the code to compile which I have written.
    I get the error: OBTComparable.java uses unchecked or unsafe operations
    this is the more detailed information of the error when I compile with -Xlint:unchecked
    OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    left.insert(insertValue);
    ^
    OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    right.insert(insertValue);
    ^
    OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return left.find(findValue);
    ^
    OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return right.find(findValue);
    ^
    and here is my code for the class
    public class OBTComparable<OBTType extends Comparable<OBTType>>
      // A tree is either empty or not
      private boolean empty;
      // If the tree is not empty then it has
      // a value, a left and a right.
      // These are not used it empty == true
      private OBTType value;
      private OBTComparable left;
      private OBTComparable right;
      // Create an empty tree.
      public OBTComparable()
        setEmpty();
      } // OBTComparable
      // Make this tree into an empty tree.
      private void setEmpty()
        empty = true;
        value = null; // arbitrary
        left = null;
        right = null;
      } // setEmpty
      // See if this is an empty (Sub)tree.
      public boolean isEmpty()
      { return empty; }
      // Get the value which is here.
      public OBTType getValue()
      { return value; }
      // Get the left sub-tree.
      public OBTComparable getLeft()
      { return left; }
      // Get the right sub-tree.
      public OBTComparable getRight()
      { return right; }
      // Store a value at this position in the tree.
      private void setValue(OBTType requiredValue)
        if (empty)
          empty = false;
          left = new OBTComparable<OBTType>(); // Makes a new empty tree.
          right = new OBTComparable<OBTType>(); // Makes a new empty tree.
        } // if
        value = requiredValue;
      } // setValue
      // Insert a value, allowing multiple instances.
      public void insert(OBTType insertValue)
        if (empty)
          setValue(insertValue);
        else if (insertValue.compareTo(value) < 0)
          left.insert(insertValue);
        else
          right.insert(insertValue);
      } // insert
      // Find a value
      public boolean find(OBTType findValue)
        if (empty)
          return false;
        else if (findValue.equals(value))
          return true;
        else if (findValue.compareTo(value) < 0)
          return left.find(findValue);
        else
          return right.find(findValue);
      } // find
    } // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
    If anyone can help me with my problem that would be great!
    Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
    Thanks in advance
    David

    I have good news and undecided news.
    First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
    In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
    The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.

  • Assign Object to class with characteristic values ?

    Hi All,
    I want to assign object to class with characteristic values. I found CL20N transaction for performing the same. Is there any BDC , BAPI to upload the same.
    Thanks & Regards,
    Navneeth K.

    Hi,
    try as below
        CALL FUNCTION 'CLAF_CLASSIFICATION_OF_OBJECTS'
          EXPORTING
            classtext            = 'X'
            classtype            = w_classtype  "Class type
            language             = sy-langu
            object               = w_object     "Object Matnr + Batch
            objecttable          = 'MARA'     "As requirement
            change_service_clf   = 'X'
            inherited_char       = ' '
            change_number        = ' '
          TABLES
            t_class              = t_class
            t_objectdata         = t_objectdata
            i_sel_characteristic = i_sel_characteristic
            t_no_auth_charact    = t_no_auth_charact.
        IF sy-subrc <> 0.
        ENDIF.
    *     Create with reference-----------------------
          w_objectkeynew = wa_inputfile-to_matnr.
          CALL FUNCTION 'BAPI_OBJCL_CREATE'
            EXPORTING
              objectkeynew    = w_objectkeynew
              objecttablenew  = 'MARA'
              classnumnew     = w_classnum
              classtypenew    = w_classtype
            TABLES
              allocvaluesnum  = t_allocvaluesnum
              allocvalueschar = t_allocvalueschar
              allocvaluescurr = t_allocvaluescurr
              return          = t_lreturn.
    "or
    BAPI_OBJCL_CHANGE              Classification BAPI: Change Assignment
    Prabhudas

  • Help with Declaring a Class with a Method and Instantiating an Object

    hello all i am having trouble understanding and completing a lab tutorial again!
    im supposed to compile an run this code then save work to understand how to declare aclass with a method an instantiate an object of the class with the following code
    // Program 1: GradeBook.java
    // Class declaration with one method.
    public class GradeBook
    // display a welcome message to the GradeBook user
    public void displayMessage()
    System.out.println( "Welcome to the Grade Book!" );
    } // end method displayMessage
    } // end class GradeBook
    // Program 2: GradeBookTest4.java
    // Create a GradeBook object and call its displayMessage method.
    public class GradeBookTest
    // main method begins program execution
    public static void main( String args[] )
    // create a GradeBook object and assign it to myGradeBook
    GradeBook myGradeBook = new GradeBook();
    // call myGradeBook's displayMessage method
    myGradeBook.displayMessage();
    } // end main
    } // end class GradeBookTest4
    i saved above code as shown to working directory filename GradeBookTest4.java
    C:\Program Files\Java\jdk1.6.0_11\bin but recieved error message
    C:\Program Files\Java\jdk1.6.0_11\bin>javac GradeBook4a.java GradeBookTest4.java
    GradeBookTest4.java:2: class, interface, or enum expected
    ^
    GradeBookTest4.java:27: reached end of file while parsing
    ^
    2 errors
    can someone tell me where the errors are because for class or interface expected message i found a solution which says 'class? or 'interface' expected is because there is a missing { somewhere much earlier in the code. i dont know what "java:51: reached end of file while parsing " means or what to do to fix ,any ideas a re appreciated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Doesn't solve your problem, but this works for me...
    public class GradeBook
      public void displayMessage() {
        System.out.println( "Welcome to the Grade Book!" );
      public static void main( String args[] ) {
        try {
          GradeBook gradeBook = new GradeBook();
          gradeBook.displayMessage();
        } catch (Exception e) {
          e.printStackTrace();
    }

  • Need help with class object? Please somoen

    hey guys,
    It's been few days since i'm working on making a small bingogame program but i'm getting stuck frequantly.
    I've different classes, in the main class i'm asking the user to input number of players who would like to play then i'm asking the player's name and how many bingoCards each player wants.
    I'm stroing all that info in a BingoPlayer class's array object. But for some reason when i get out from the loop and try to retrive the info from that array it only gives me the last input entry (player's name & number of cards) at any index of the array.
    Can please someone tell me how i can store the given information for each player in that object array on different indices of the array?
    I'm providing the code where i've the problems:
    public class BingoGame
        public static BingoPlayer players[] = new BingoPlayer[5];
        public static void main() throws IOException {
            int numPlayers = 0;
            int numCards [] = new int [5];
            String name [] = new String[4];
            BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); //allows input
    // ask for the number players who wants to play
            System.out.print("Please enter the number of players in this game (2-5): ");
            numPlayers = Integer.parseInt(input.readLine());
    // make sure the entered value is within range
            while (numPlayers < 2 || numPlayers > 5) {
                System.out.println("Invalid number of players ");
                System.out.print("Please enter the number of players in this game (2-5): ");
                numPlayers = Integer.parseInt(input.readLine());
            System.out.println();
    //ask for the names and numebr of cards for entered number of players
    // and make sure the number of cards are within the range,
    //and assign the players that many cards using the BingoPlayer object 
            for (int i = 1; i <= numPlayers; i++) {
                System.out.print("Please enter name of player " + i + " : ");
                name[i] = input.readLine();
                System.out.println();
                System.out.print("Please enter the number of cards (1-5) for player " + i + " : ");
                numCards[i] = Integer.parseInt(input.readLine());
                while (numCards[i] < 1 || numCards[i] > 5) {
                    System.out.println("Invalid number of cards for the player " + i);
                    System.out.print("Please enter the number of cards (1-5) for player " + i + " : ");
                    numCards[i] = Integer.parseInt(input.readLine());
                System.out.println();
                players[i] = new BingoPlayer(name, numCards[i]);
    * here it only prints out the information for the last player, instead it should return the information for both of the player
    for (int k = 1; k <= numPlayers; k ++) {
    System.out.println(players[k]);
    //players[k].genCards();
    for example if i enter 2 players:
    Player1: name: Jami, number of cards 1
    Player2: name: Joey, number of cards 2
    in the last loop it just prints out :"Joey, 2" 2 times instead of printing out: "Jami, 1" & "Joey, 2"
    Please someone help! i really need to complete this within 2 days. Thanks in advance

    Without seeing BingoPlayer's implementation, all it
    would be would be a guess.
    My guess: The name and numCards members of that class
    are declared as static, so all instances share the
    same values.Thanks it worked, declaring them static was the main probelm..thank you very much

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

Maybe you are looking for

  • No Contact Name On New SMS

    I never noticed till I seen another post about not being able to see who sent me a sms text.  I have looked in the other options from the previous post but my 8530 does not apear to have those settings any other ideas?  Carrier is Us Cellular if that

  • Software Update Glitches

    My BlackBerry Q10 worked perfectly before I installed the new software update. Now that I have version 10.2.1.2179, my keys are messed up: the Q & A keys are backwards (when I press the Q key I get an "A" and vice versa). Same thing with my W & Z key

  • Satellite A500 - Upgrading from Vista to Windows 7 error

    I'm trying to upgrade my Vista Home Premium to Windows 7 Home Premium via the Toshiba Upgrade Assistance so it will automatically download some Toshiba's utilites and software. At the start of launching it, an error message "This model does not suppo

  • Initialization error : class file has wrong version 49.0, should be 45.3 or

    I have Jdeveloper Base installation and JDK 1.5..the classpath and JAVA_HOME environment variables are set to the respective JDK1.5\bin folders. Even then when i try to make a web application, with a simple JSP page i get the following error : Initia

  • 7.0.2 update - won't let me use my 3g in apple related apps

    since i updated to IOS 7.0.2 - I can't use it to login in any apple related apps or download in appstore... what should i do? Settings are correct - all are on Itunes and appstore 3G on  and data... tried resetting and tried Restore. still now good.