HELP! "array required, but object found" :S

Halo I'm new to Java and on one of my exercises I'm getting the following compile error and don't know why :S
"array required but Deck found"
Here is the code:
//Card.java this defines the Card class and object
public class Card {
private final int rank;
private final int suit;
// Kinds of suits
public final static int DIAMONDS = 1;
public final static int CLUBS = 2;
public final static int HEARTS = 3;
public final static int SPADES = 4;
// Kinds of ranks
public final static int ACE = 1;
public final static int DEUCE = 2;
public final static int THREE = 3;
public final static int FOUR = 4;
public final static int FIVE = 5;
public final static int SIX = 6;
public final static int SEVEN = 7;
public final static int EIGHT = 8;
public final static int NINE = 9;
public final static int TEN = 10;
public final static int JACK = 11;
public final static int QUEEN = 12;
public final static int KING = 13;
public Card(int rank, int suit) {
assert isValidRank(rank);
assert isValidSuit(suit);
this.rank = rank;
this.suit = suit;
public int getSuit() {
return suit;
public int getRank() {
return rank;
public static boolean isValidRank(int rank) {
return ACE <= rank && rank <= KING;
public static boolean isValidSuit(int suit) {
return DIAMONDS <= suit && suit <= SPADES;
public static String rankToString(int rank) {
switch (rank) {
case ACE:
return "Ace";
case DEUCE:
return "Deuce";
case THREE:
return "Three";
case FOUR:
return "Four";
case FIVE:
return "Five";
case SIX:
return "Six";
case SEVEN:
return "Seven";
case EIGHT:
return "Eight";
case NINE:
return "Nine";
case TEN:
return "Ten";
case JACK:
return "Jack";
case QUEEN:
return "Queen";
case KING:
return "King";
default:
return null;
public static String suitToString(int suit) {
switch (suit) {
case DIAMONDS:
return "Diamonds";
case CLUBS:
return "Clubs";
case HEARTS:
return "Hearts";
case SPADES:
return "Spades";
default:
return null;
// Deck.java creates a deck of cards:P
import java.util.*;
public class Deck {
public static int numSuits = 4;
public static int numRanks = 13;
public static int numCards = numSuits * numRanks;
public Card[][] cards;
public Deck() {
cards = new Card[numSuits][numRanks];
for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
for (int rank = Card.ACE; rank <= Card.KING; rank++) {
cards[suit-1][rank-1] = new Card(rank, suit);
public Card getCard(int suit, int rank) {
return cards[suit-1][rank-1];
//AND finally, DisplayDeck.java that creates a deck of cards and display the cards of a deck:P
import java.util.*;
public class DisplayDeck {
public static void main(String[] args) {
Deck bobbysDeck = new Deck();
for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
for (int rank = Card.ACE; rank <= Card.KING; rank++) {
System.out.format("%s of %s%n",
Card.rankToString(bobbysDeck[suit-1][rank-1].getrank()), //<---here is where I get the error
Card.suitToString(bobbysDeck[suit-1][rank-1].getsuit())); // <----and here too
bobbysDeck is an array, so why is it giving me this compile error? Thank you very much for your help.

For the benefit of others, here is Deck displayed with code tags:
public class Deck
  public static int numSuits = 4;
  public static int numRanks = 13;
  public static int numCards = numSuits * numRanks;
  public Card[][] cards;
  public Deck()
    cards = new Card[numSuits][numRanks];
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
      for (int rank = Card.ACE; rank <= Card.KING; rank++)
        cards[suit - 1][rank - 1] = new Card(rank, suit);
  public Card getCard(int suit, int rank)
    return cards[suit - 1][rank - 1];
}You'll see that Deck holds an array of Card objects in its cards field. You could if you desired directly access that field and use that as an array like so:
  public static void main(String[] args)
    Deck bobbysDeck = new Deck();
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
      for (int rank = Card.ACE; rank <= Card.KING; rank++)
        Card card = bobbysDeck.cards[suit - 1][rank - 1];
        System.out.format("%s of %s%n",
            Card.rankToString(card.getRank()),
            Card.suitToString(card.getSuit()));
  }but this allows outside classes to mess around with the innards of the Deck class in ways that we cannot control and can cause nasty bugs to appear that are very hard to identify and remove. Some class could for instance delete all the Card objects in cards. Much better and much safer is to make Deck's card variable a private variable and to only get the information through public methods, methods that allow the Deck class to control access. Notice that with this method, we can only get the card information; we can't delte or change it. So better is this:
  public static void main(String[] args)
    Deck bobbysDeck = new Deck();
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
      for (int rank = Card.ACE; rank <= Card.KING; rank++)
        Card card = bobbysDeck.getCard(suit, rank);
        System.out.format("%s of %s%n",
            Card.rankToString(card.getRank()),
            Card.suitToString(card.getSuit()));
  }

Similar Messages

  • Array required, passing as an arguement to contructor which wants an array

    Hello again, can you help me with this?
    here is the error
    C:\jDevl\GameTest.java:19: array required, but Lot649.Ticket1 found
              lotto[0] = new Ticket1(1,2,12,1982, 3, 11, 12, 14, 41, 43, 13);
    ^
    C:\jDevl\GameTest.java:20: array required, but Lot649.Ticket1 found
              lotto[1] = new Ticket1(2,2,19,1982, 8, 33, 36, 37, 39, 41, 9);
    ^
    C:\jDevl\GameTest.java:21: array required, but Lot649.Ticket1 found
              lotto[2] = new Ticket1(3,2,26,1982, 1, 6, 23, 24, 27, 39, 34);
    ^
    HERE IS THE GAMETEST CODE, I BELIEVE THE PROBLEM IS WITH MY CONSTRUCTOR
    IN THE TICKET CLASS...
    public class GameTest{
         public static void main( String args[]){
              String result = "";
              //fill the lottery array with 5 ticket objects
              Ticket1 lotto = new Ticket1();
              Ticket1 t = new Ticket1();
                                  //recNo,mmddyr, n1, n2, n3, n4, n5, n6, n7}
              lotto[0] = new Ticket1(1,2,12,1982, 3, 11, 12, 14, 41, 43, 13);
              lotto[1] = new Ticket1(2,2,19,1982, 8, 33, 36, 37, 39, 41, 9);
              lotto[2] = new Ticket1(3,2,26,1982, 1, 6, 23, 24, 27, 39, 34);
              lotto[3] = new Ticket1(4,3,3,1982, 3, 9, 10, 13, 20, 43, 34);
              lotto[4] = new Ticket1(5,3,3,1982, 3, 11, 12, 14, 41, 43, 14);HERE IS THE TICKET CLASS CODE... dang those arrays, i believe i have messed up somehow with the arrays passing as args.
    public class Ticket1{
         private int recNum;
         private int mm;
         private int dd;
         private int yy;
         private int nArray[] = new int[7];
         public Ticket1(){
                        recNum = 0;
                        //drawDate = dDay.getDate();
                        //Date dD = new Date();
                        //drawDate = dDay.getDate();
                        mm = 1;
                        dd = 1;
                        yy = 1900;
                        nArray[0] = 0;
                        nArray[1] = 0;
                        nArray[2] = 0;
                        nArray[3] = 0;
                        nArray[4] = 0;
                        nArray[5] = 0;
                        nArray[6] = 0;
         }//end of constructor
         public Ticket1( int rec, int mon, int day, int year, int n1, int n2,
                         int n3, int n4, int n5, int n6, int n7){
              recNum = rec;
              //drawDate = dDay.getDate();
              //Date dD = new Date();
              //drawDate = dDay.getDate();
              mm = mon;
              dd = day;
              yy = year;
              nArray[0] = checkNum(n1);
              nArray[1] = checkNum(n2);
              nArray[2] = checkNum(n3);
              nArray[3] = checkNum(n4);
              nArray[4] = checkNum(n5);
              nArray[5] = checkNum(n6);
              nArray[6] = checkNum(n7);
         }//end of ticket constructor
         public Ticket1( int recA, int monA, int dayA, int yearA, int arrayName[] ){
              recNum = recA;
              mm = monA;
              dd = dayA;
              yy = yearA;
              nArray[0] = arrayName[0];
              nArray[1] = arrayName[1];
              nArray[2] = arrayName[2];
              nArray[3] = arrayName[3];
              nArray[4] = arrayName[4];
              nArray[5] = arrayName[5];
              nArray[6] = arrayName[6];
         }//end of Ticket1 constructor

    Ticket1 lotto = new Ticket1();lotto is not delcare as an array and you wants it to act like an array?
    lotto[0] = new Ticket1(1,2,12,1982, 3, 11, 12, 14, 41, 43, 13);
    lotto[1] = new Ticket1(2,2,19,1982, 8, 33, 36, 37, 39, 41, 9);you should do :
    Ticket1 lotto[] = new Ticket1[5];

  • Java plugin for business objects not found. When trying to modify a business objects query, it says a plugin is required but none are found. What do I need to do?

    I downloaded firefox 4.0 and attempted to use business objects. A screen comes up saying that a plugin is required but when I click on the screen, it say's no plugin is found. I am using the latest version of Java but it seems that the plugin is not there.

    There is workaround.
    Enter “about:config” in the browser’s address bar.
    Search for “html5.parser.enable”.
    Double-click the row to set the value to “false” (row should also go bold to indicate change).
    There is a possibility that it may cause HTML5 compatibility issues down the road but it solved the issue.

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

  • Array of cfc object help

    I just picked up coldfusion about a month ago, so my
    coldfusion lingo sucks. I have been programming in C++ for over 5
    years now and will be using a lot of C++ terminology to help avoid
    any confusion. I am writing a cfc function that preforms web
    servicing. This function needs to return an object/class that is
    defined in another coldfusion function. I can do this without a
    problem if I only need to return one instance of this object.
    However, I cannot seem to return an array of this object (I need to
    return multiple instances of this object, kind of like a query, but
    for programming purposes it needs to stay as an object).
    It seems that the webservicing function hates my return type.
    If I try to make an array of the object, it does not like array or
    the object as the return type. However, when I take this function
    out of the cfc, and make it a cfm, it gets the array of objects
    just fine. So, I think I am having issues with the return type on
    the <cffunction> tag. So I came up with the idea of creating
    another object which will hold an array of the first object and
    using the second object as the return type. Here is some psuedo
    code of the function I am working on:
    <cffunction name="SelectGames" access="remote"
    returntype="ArrayOfGames" output="false">
    <!-- arguments --->
    <!--- query --->
    <cfobject component = "myArray" name>
    <cfobject component="games" name="test">
    <cfset counter = 0>
    <cfloop query="getevents">
    <cfset counter = counter + 1>
    <cfset test.Game_id = event_id>
    <cfset test.gameDate = eventdate>
    <cfset test.Starttime = starttime>
    <cfset test.Place = place>
    <cfset test.Level = level>
    <cfset test.Sport = sport>
    <cfset test.Gender = division>
    <cfset test.Opponent = opponent_id>
    <cfset test.Type = type>
    <cfset test.Link = spec_name>
    <cfset myArray.gamesArray[counter] = test>
    </cfloop>
    <cfreturn myArray>
    </cffunction>
    It keeps telling me that it does not recognize the return
    type.
    Here are examples of the two objects I am using from the 2
    dif. cfc files:
    <cfcomponent>
    <cfproperty name="gamesArray" type="array">
    </cfcomponent>
    <cfcomponent>
    <cfproperty name="Game_id" type="numeric">
    <cfproperty name="gameDate" type="date">
    <cfproperty name="Starttime" type="string">
    <cfproperty name="Place" type="string">
    <cfproperty name="Level" type="string">
    <cfproperty name="Sport" type="string">
    <cfproperty name="Gender" type="string">
    <cfproperty name="Opponent" type="string">
    <cfproperty name="Type" type="string">
    <cfproperty name="Link" type="string">
    </cfcomponent>
    Feel free to post any questions to clear anything up, I know
    this is confusing and I probably did a poor job of explaining my
    problem. Also, if I throw this code into a cfm and try to make an
    array of games, it works, this is the code I got it to work with:
    <cfset myArray = newArray(1)>
    <cfloop query="getevents">
    <cfset counter = counter + 1>
    <cfset test.Game_id = event_id>
    <cfset test.gameDate = eventdate>
    <cfset test.Starttime = starttime>
    <cfset test.Place = place>
    <cfset test.Level = level>
    <cfset test.Sport = sport>
    <cfset test.Gender = division>
    <cfset test.Opponent = opponent_id>
    <cfset test.Type = type>
    <cfset test.Link = spec_name>
    <cfset myArray[counter] = test>
    </cfloop>
    I guess my problem is I do not know how to specify a type for
    an array.

    The return type of this FUNCTION would be returnType="array".
    No matter
    what kind of data the array contained.
    That's what I get for fast proofing.
    Ian Skinner wrote:
    > I would have to play with your code more if this does
    not clear it up
    > for you, but lets start with this simple concept first.
    >
    > You mentioned "typing the array" several times.
    ColdFusion is typeless,
    > you don't type an array, it is just array. An array of
    strings is the
    > same as an array of integers which is the same as an
    array of objects.
    >
    > So if you had a function something like this.
    >
    > <cffunction returnType="array" ...>
    > <cfset theArray = arrayNew()>
    >
    > <cfloop ...>
    > <cfset arrayAppend(theArray, newObject)>
    > </cfloop>
    >
    > <cfreturn theArray>
    > </cffunction>
    >
    > The return type of this function would be
    returnType="array". No matter what
    > kind of data the array contained.
    >
    > mwiley63 wrote:
    >> I just picked up coldfusion about a month ago, so my
    coldfusion lingo
    >> sucks. I have been programming in C++ for over 5
    years now and will
    >> be using a lot of C++ terminology to help avoid any
    confusion. I am
    >> writing a cfc function that preforms web servicing.
    This function
    >> needs to return an object/class that is defined in
    another coldfusion
    >> function. I can do this without a problem if I only
    need to return
    >> one instance of this object. However, I cannot seem
    to return an
    >> array of this object (I need to return multiple
    instances of this
    >> object, kind of like a query, but for programming
    purposes it needs to
    >> stay as an object).
    >> It seems that the webservicing function hates my
    return type. If I
    >> try to make an array of the object, it does not like
    array or the
    >> object as the return type. However, when I take this
    function out of
    >> the cfc, and make it a cfm, it gets the array of
    objects just fine.
    >> So, I think I am having issues with the return type
    on the
    >> <cffunction> tag. So I came up with the idea
    of creating another
    >> object which will hold an array of the first object
    and using the
    >> second object as the return type. Here is some
    psuedo code of the
    >> function I am working on:
    >>
    >> <cffunction name="SelectGames" access="remote"
    >> returntype="ArrayOfGames" output="false">
    >> <!-- arguments --->
    >> <!--- query --->
    >> <cfobject component = "myArray" name>
    >> <cfobject component="games" name="test">
    >> <cfset counter = 0>
    >> <cfloop query="getevents">
    >> <cfset counter = counter + 1>
    >> <cfset test.Game_id = event_id>
    >> <cfset test.gameDate = eventdate>
    >> <cfset test.Starttime = starttime>
    >> <cfset test.Place = place>
    >> <cfset test.Level = level>
    >> <cfset test.Sport = sport>
    >> <cfset test.Gender = division>
    >> <cfset test.Opponent = opponent_id>
    >> <cfset test.Type = type>
    >> <cfset test.Link = spec_name>
    >> <cfset myArray.gamesArray[counter] = test>
    >> </cfloop>
    >> <cfreturn myArray>
    >> </cffunction>
    >>
    >> It keeps telling me that it does not recognize the
    return type.
    >> Here are examples of the two objects I am using from
    the 2 dif. cfc
    >> files:
    >> <cfcomponent>
    >> <cfproperty name="gamesArray" type="array">
    >> </cfcomponent>
    >> <cfcomponent>
    >> <cfproperty name="Game_id" type="numeric">
    >> <cfproperty name="gameDate" type="date">
    >> <cfproperty name="Starttime" type="string">
    >> <cfproperty name="Place" type="string">
    >> <cfproperty name="Level" type="string">
    >> <cfproperty name="Sport" type="string">
    >> <cfproperty name="Gender" type="string">
    >> <cfproperty name="Opponent" type="string">
    >> <cfproperty name="Type" type="string">
    >> <cfproperty name="Link" type="string">
    >> </cfcomponent>
    >>
    >> Feel free to post any questions to clear anything
    up, I know this is
    >> confusing and I probably did a poor job of
    explaining my problem.
    >> Also, if I throw this code into a cfm and try to
    make an array of
    >> games, it works, this is the code I got it to work
    with:
    >> <cfset myArray = newArray(1)>
    >> <cfloop query="getevents">
    >> <cfset counter = counter + 1>
    >> <cfset test.Game_id = event_id>
    >> <cfset test.gameDate = eventdate>
    >> <cfset test.Starttime = starttime>
    >> <cfset test.Place = place>
    >> <cfset test.Level = level>
    >> <cfset test.Sport = sport>
    >> <cfset test.Gender = division>
    >> <cfset test.Opponent = opponent_id>
    >> <cfset test.Type = type>
    >> <cfset test.Link = spec_name>
    >> <cfset myArray[counter] = test>
    >> </cfloop>
    >>
    >> I guess my problem is I do not know how to specify a
    type for an array.
    >>

  • Array of CreditCard objects - PLEASE HELP!

    My situation is this: I need to create an array of CreditCard objects. The problem is that when I try to invoke the methods getName, getNumber, or getLimit, the compiler recognizes the array (cardholders) as a variable.
    My coding is this.
    for(int i=0;fileInput.hasNext();i++)
         CreditCard[] cardholders = new CreditCard[records];
         int cardNum = Integer.parseInt(fileInput.next());
         String cardName = fileInput.nextLine();
         double cardLimit = Double.parseDouble(fileInput.nextLine());
         cardholders[i] = new CreditCard(cardNum, cardName, cardLimit);
    But when I try to access a CreditCard object, through cardholders[4] (for example), the error cannot find symbol appears. PLEASE HELP ITS DRIVING ME CRAZY.
    THANKS

    You are lacking basic Java knowledge, micksabox. The following tutorial is on Arrays in Java. The one after on the Java Collections Framework, you might want to learn about as the better solution for working with sets and lists of objects in Java.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
    http://java.sun.com/docs/books/tutorial/collections/index.html

  • I have installed flash player on my hp laptop windows 7 i am playing games but then all off a sudden it tells me that flash player is not found 11.3.0 version is required but i have this already installed now i cant play my games

    i have installed flash player on my hp laptop windows 7 i am playing games but then all off a sudden it tells me that flash player is not found 11.3.0 version is required but i have this already installed now i cant play my games. I have uninstalled and reinstalled it but it still not working please can any one help.

    MatchingNode
    YOUR SYSTEM INFORMATION
    Your Flash Version
    17.0.0.134
    Your browser name
    Internet Explorer
    Your Operating System (OS)
    Windows (Windows 7)
    I cant take a screen shot of the flash player update tab as it wont let me and wont let me copy and paste sorry
    i am using internet explore browser and trying to play facebook games thats where i am facing the issues.

  • Help, store an array of cd objects

    im doing a java project on creating a music cd database, i need to store an array of cd objects, each entry in the array will be a single object for a cd.
    The objects are: Artist, Album, No of tracks
    I need some help with this, thanks
    here's the code ive done so far:
    import javax.swing.JOptionPane;
    class Cd1
         public static void main (String[] args)
              int menu_choice;
              CdRecord one = new CdRecord();
              one.artist_name = JOptionPane.showInputDialog("Enter artist name.");
              one.album_name = JOptionPane.showInputDialog("Enter album name.");
              one.no_of_tracks =Integer.parseInt(JOptionPane.showInputDialog("Enter the number of tracks on the album"));
         one.printCdRecord();          
    class CdRecord
         public String artist_name;
         public String album_name;
         public int no_of_tracks;
    public CdRecord (String artist, String album, int tracks, int year)
         artist_name = artist;
         album_name = album;
         no_of_tracks = tracks;
    public CdRecord()
    artist_name = "A";
    album_name = "B";
    no_of_tracks = 0;
    public void printCdRecord ()
    String o = "Artist Name: " + artist_name + "\nAlbum Name: " album_name"\nNo. Of Tracks: " + no_of_tracks;;
    System.out.println(o);
    }

    where should i put this in my code?this part would normally be a class field, accessible from many parts of the class
    java.util.List<CdRecord> records;to it may look something like this
    class Cd1
      private java.util.List<CdRecord> records;//and use constructor to create
      //or
      private java.util.List<CdRecord> records = new java.util.ArrayList<CdRecord>();
      ...as is, the above will cause you a problem because you have most of your code in main() which is static.
    before you go much further, rethink your program design:
    - your class name is Cd1, which would indicate a single CD, but you're doing a CD database so call it CdInventory, CdCollection, etc
    - the only code you want in main() is to start the program, so that would be new CdInventory(), nothing more (unless creating a GUI)
    - how are you going to get new records - a GUI with buttons add/edit/delete, or the console.
    - are you going to save new/edited records to a file (the database), and read existing data back into the program at startup
    - basically how you go about the above determines what you have in the constructor of the program (and do not use main() for this)

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • Moved Music to New Hard Drive - Required folder not found??? pls help

    Hello
    I have recently purchased a new external hard drive as my crappy Dell was full to the brim with music.
    I have moved all my music files over to the hard drive and re installed itunes.
    Now when i drag my music folder into the itunes library it updates but the shortly after an error message occurs that says:-
    'Itunes Libray music file cannot be saved. Required folder not found'
    Previously i have saved my itunes folder within my music folder?.
    Now everytime i close down itunes all my music has gone from it!??
    Any suggestions....sorry if being really ignorant..not too profficient on computers..
    Thanks in advance.
    Sam
    Dell PC Windows XP
    Dell PC   Windows XP  

    I think itunes by default looks inside you my music folder. In the itunes preferences screen there is an option to select a new folder to your library. Change the path to the music folder on your external drive. Make sure to always have the drive turned on before launching itunes though.
    You may also be able to replace the my music folder with a shortcut to the music folder on the external drive. This behavior may not work in windows though so I'm not sure.

  • Why ava.lang.reflect.Array.newInstance() returns Object, but not Object[]?

    It is interesting why java.lang.reflect.Array.newInstance() returns
    Object, but not more specific Object[]?

    Array.newInstance(int.class, length)

  • Need Help ASAP! TV Show won't sync, required disc not found

    I need some help!!! I am trying to sync a TV SHow to my iPod and I can't get it to work. For some reason in iTunes, I have to completely unplug and plug in my iPod anytime I want it to sync, pressing the sync button does not work, neither does pressing the apply button after checking the TV show that I want to sync. SInce I don't have to update any settings for music, this isn't a problem, I just unplug my iPod and plug it back in and it syncs automatically. The error message I get when trying to sync Shows, or videos or anything where you have to update is Can't sync iPod required disc not found. If someone could respond to this right away, I would appreciate it as we are going to be traveling today, and I would love to have something to watch during my four hour flight!

    Welcome to Apple Discussions!
    See if the steps listed here help...
    http://support.apple.com/kb/TS1539
    btabz

  • I have just installed Illustrator CS6 yesterday, but I found it was in French. Could help me figure out how to change the language into English?

    I have just installed Illustrator CS6 yesterday, but I found it was in French. Could help me figure out how to change the language into English?
    I got my series number from my Institut (which is in Paris, FR). I do not use Creative Cloud.
    When I was installing the software, I cannot select a language.
    Could you help me with my problem? Do I have to get a different series number?

    lunc,
    You will have to get a new application in English, to replace the French one.
    You, or your Institute will have to get help from Adobe, I am afraid.
    You may try a chat here,
    Get help with orders, refunds, and exchanges (non-CC, chat open between 5AM and 7PM PST/PDT on workdays)
    http://helpx.adobe.com/x-productkb/global/service-b.html
    or (have your Institute) talk to Adobe in France
    http://helpx.adobe.com/adobe-connect/adobe-connect-phone-numbers.html
    If you fail to get any help, please report back here, and I will ask a special forum staff friend to try to find the right one at Adobe to have things sorted out.

  • Good evening! I bought an iphone 4 from a stranger and I want to decode it, but I found out that is blacklist. Can you help me, please?

    Good evening! I bought an iphone 4 from a stranger and I want to decode it, but I found out that is blacklist. Can you help me, please?

    sylvyu008 wrote:
    Good evening! I bought an iphone 4 from a stranger and I want to decode it, but I found out that is blacklist. Can you help me, please?
    That means that you bought a stolen phone.

  • I can't seem to get individual elements when comparing 2 arrays using Compare-Object

    My backup software keeps track of servers with issues using a 30 day rolling log, which it emails to me once a week in CSV format. What I want to do is create a master list of servers, then compare that master list against the new weekly lists to identify
    servers that are not in the master list, and vice versa. That way I know what servers are new problem and which ones are pre-existing and which ones dropped off the master list. At the bottom is the entire code for the project. I know it's a bit much
    but I want to provide all the information, hopefully making it easier for you to help me :)
    Right now the part I am working on is in the Compare-NewAgainstMaster function, beginning on line 93. After putting one more (fake) server in the master file, the output I get looks like this
    Total entries (arrMasterServers): 245
    Total entries (arrNewServers): 244
    Comparing new against master
    There are 1 differences.
    InputObject SideIndicator
    @{Agent= Virtual Server in vCenterServer; Backupse... <=
    What I am trying to get is just the name of the server, which should be $arrDifferent[0] or possibly $arrDifferent.Client. Once I have the name(s) of the servers that are different, then I can do stuff with that. So either I am not accessing the array
    right, building the array right, or using Compare-Object correctly.
    Thank you!
    Sample opening lines from the report
    " CommCells > myComCellServer (Reports) >"
    " myComCellServer -"
    " 30 day SLA"
    CommCell Details
    " Client"," Agent"," Instance"," Backupset"," Subclient"," Reason"," Last Job Id"," Last Job End"," Last Job Status"
    " myServerA"," vCenterServer"," VMware"," defaultBackupSet"," default"," No Job within SLA Period"," 496223"," Nov 17, 2014"," Killed"
    " myServerB"," Oracle Database"," myDataBase"," default"," default"," No Job within SLA Period"," 0"," N/A"," N/A"
    Entire script
    # things to add
    # what date was server entered in list
    # how many days has server been on list
    # add temp.status = pre-existing, new, removed from list
    # copy sla_master before making changes. Copy to archive folder, automate rolling 90 days?
    ## 20150114 Created script ##
    #declare global variables
    $global:arrNewServers = @()
    $global:arrMasterServers = @()
    $global:countNewServers = 1
    function Get-NewServers
    Param($path)
    Write-Host "Since we're skipping the 1st 6 lines, create test to check for opening lines of report from CommVault."
    write-host "If not original report, break out of script"
    Write-Host ""
    #skip 5 to include headers, 6 for no headers
    (Get-Content -path $path | Select-Object -Skip 6) | Set-Content $path
    $sourceNewServers = get-content -path $path
    $global:countNewServers = 1
    foreach ($line in $sourceNewServers)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0].Substring(2, $tempLine[0].Length-3)
    $temp.Agent = $tempLine[1].Substring(2, $tempLine[1].Length-3)
    $temp.Backupset = $tempLine[3].Substring(2, $tempLine[3].Length-3)
    $temp.Reason = $tempLine[5].Substring(2, $tempLine[5].Length-3)
    #write temp object to array
    $global:arrNewServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countNewServers ++
    Write-Host ""
    $exportYN = Read-Host "Do you want to export new servers to new master list?"
    $exportYN = $exportYN.ToUpper()
    if ($exportYN -eq "Y")
    $exportPath = Read-Host "Enter full path to export to"
    Write-Host "Exporting to $($exportPath)"
    foreach ($server in $arrNewServers)
    $newtext = $Server.Client + ", " + $Server.Agent + ", " + $Server.Backupset + ", " + $Server.Reason
    Add-Content -Path $exportPath -Value $newtext
    function Get-MasterServers
    Param($path)
    $sourceMaster = get-content -path $path
    $global:countMasterServers = 1
    foreach ($line in $sourceMaster)
    #declare array to hold object temporarily
    $temp = @{}
    $tempLine = $line.Split(",")
    #get and assign values
    $temp.Client = $tempLine[0]
    $temp.Agent = $tempLine[1]
    $temp.Backupset = $tempLine[2]
    $temp.Reason = $tempLine[3]
    #write temp object to array
    $global:arrMasterServers += New-Object -TypeName psobject -Property $temp
    #increment counter
    $global:countMasterServers ++
    function Compare-NewAgainstMaster
    Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    Write-Host "Total entries (arrNewServers): $($countNewServers)"
    Write-Host "Comparing new against master"
    #Compare-Object $arrMasterServers $arrNewServers
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Write-Host "There are $($arrDifferent.Count) differences."
    foreach ($item in $arrDifferent)
    $item
    ## BEGIN CODE ##
    cls
    $getMasterServersYN = Read-Host "Do you want to get master servers?"
    $getMasterServersYN = $getMasterServersYN.ToUpper()
    if ($getMasterServersYN -eq "Y")
    $filePathMaster = Read-Host "Enter full path and file name to master server list"
    $temp = Test-Path $filePathMaster
    if ($temp -eq $false)
    Read-Host "File not found ($($filePathMaster)), press any key to exit script"
    exit
    Get-MasterServers -path $filePathMaster
    $getNewServersYN = Read-Host "Do you want to get new servers?"
    $getNewServersYN = $getNewServersYN.ToUpper()
    if ($getNewServersYN -eq "Y")
    $filePathNewServers = Read-Host "Enter full path and file name to new server list"
    $temp = Test-Path $filePathNewServers
    if ($temp -eq $false)
    Read-Host "File not found ($($filePath)), press any key to exit script"
    exit
    Get-NewServers -path $filePathNewServers
    #$global:arrNewServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrNewServers): $($countNewServers)"
    #Write-Host ""
    #$global:arrMasterServers | format-table client, agent, backupset, reason -AutoSize
    #Write-Host ""
    #Write-Host "Total entries (arrMasterServers): $($countMasterServers)"
    #Write-Host ""
    Compare-NewAgainstMaster

    do not do this:
    $arrDifferent = @(Compare-Object $arrMasterServers $arrNewServers)
    Try this:
    $arrDifferent = Compare-Object $arrMasterServers $arrNewServers -PassThru
    ¯\_(ツ)_/¯
    This is what made the difference. I guess you don't have to declare arrDifferent as an array, it is automatically created as an array when Compare-Object runs and fills it with the results of the compare operation. I'll look at that "pass thru" option
    in a little more detail. Thank you very much!
    Yes - this is the way PowerShell works.  You do not need to write so much code once you understand what PS can and is doing.
    ¯\_(ツ)_/¯

Maybe you are looking for

  • Use of JCo

    Hello Everyone,                        I m developing one portal application using NWDS. This application connects to backend SAP R/3 system & fetches the data in some table. i have decided to use JCo to connect to R/3 system. But in my code it gives

  • Still i am looking for the solution (its urgent guys)

    for the following code i am geting details of all the documents which are opened on the basis of p_date1 but i also need those documents which are cleared before this date or on this date. so what to do? *& Report  Z_VENDOR AGEING                    

  • Java.security.AccessControlException while trying to run the server app

    ok, pretty new with java and rmi, so I wanted to run the application from the sun rmi tutorial http://java.sun.com/docs/books/tutorial/rmi/TOC.html. It all builds ok, i run the rmiregistry ,but when i try to run the server i get : java.security.Acces

  • Java.lang.AbstractMethodError: javax.servlet.jsp.JspFactory.getJspApplicati

    Hi, I have an application which is executing properly in jboss 3.2.5 but as we are trying to upgrade the jboss version i am getting above mentioned error. The application is deployed in jboss as an ear file and the ear contains one jar file that has

  • Printers deployed via GPO - users' default printers switch back...

    Windows 2008 R2 Server (remote office server acting as a DC, GC and print server); clients run Windows 7 Enterprise x64 (users have roaming profiles with folder redirection) I deployed 5 network printers using Group Policy (per machine): Printer1, Pr