Making a class deck

i am working to make a class deck.... stuck in between.
Here is what is required
Constructor Detail
DeckOfCards
public DeckOfCards()
creates an unshuffled deck of cards order of suites: Club, Spade, Heart, Diamond
Method Detail
getTopCard
public Card getTopCard()
removes the top card from the deck
Returns:
provides the card that was top of the deck
replaceCard
public void replaceCard(Card usedCard)
places a card at the bottom of the deck
Parameters:
usedCard - card to be added to the bottom of the deck
shuffleDeck
public void shuffleDeck()
randomises the order of cards in the deck
Here is my code     import java.util.Random;
     public class Deck {
          private int top;     // pointer to the next Card to deal
          private Card [] deck;     // collection of Card objects
              private static Random gen = new Random();
               public Deck() {
                // Create an unshuffled deck of cards.
            deck = new Card[52];
            int cardCt = 0; // How many cards have been created so far.
            for ( int suit = 0; suit <= 3; suit++ ) {
               for ( int value = 1; value <= 13; value++ ) {
                  deck[cardCt] = new Card(value,suit);
                  cardCt++;
            cardsUsed = 0;
         public int getTop(){
                     return top;
              public void shuffle() {
                     for( int i = 0; i < deck.length; i++ ){
                          int rand = gen.nextInt(52-i)+i;
                          Card temp = deck;
               deck[i] = deck[rand];
               deck[rand] = temp;           
What can i do now...??

You could implement the rest of the required methods next. Unless you just chopped off the rest of the code and you really did that already.
Or you could throw out the method that you did already implement, but wasn't called for in the requirements.

Similar Messages

  • Need help making this class Runnable.

    Hello,
    This class (see below) is working fine the way it is but I have a little problem, I need to execute aprox 500+ commands and each command takes between 30sec to 3 minutes to complete which translate into hours for the job to finish.
    I want to speed the process by multi-tasking and executing (possibly) all commands simultaniously by somehow making this class Threaded/Runnable (miltitasking). There must be something tricky about Runtime class and cannot figured it out.
    Your help would be highly appreciated.
    Regards,
    Ulises
    public class CmdTest {     
    public static void main(String[] args) throws java.io.IOException {
    String outFile = "./ds8300/lsvogrp.txt";
    PrintWriter bout = null;
    try {
    bout     = new PrintWriter(                         new FileWriter(new File(outFile)));     
    } catch (IOException e) {
         e.printStackTrace();
    Runtime run = Runtime.getRuntime();
    run.traceMethodCalls(true);
    Process proc2 = run.exec("cmd /c dscli -user user -passwd psw" + "lsvolgrp -l");
    BufferedWriter ot = new BufferedWriter(
    new OutputStreamWriter(proc2.getOutputStream()));
    BufferedReader br = new BufferedReader(
    new InputStreamReader(proc2.getInputStream()));
    BufferedReader er = new BufferedReader(
    new InputStreamReader(proc2.getErrorStream()));
    try {
    String s;
    while((s=br.readLine())!=null) {
         System.out.println(""+s);
         bout.println(s);
    while((s=er.readLine())!=null) System.out.println("ERR:"+s);
    bout.close();
    System.exit(0);
    }catch (Exception ie) { //catch (InterruptedException ie) {
    System.out.println("Interrupted:"+ie.getMessage());}
    }

    Seems like the same question you asked last year.
    http://forum.java.sun.com/thread.jspa?threadID=5181153&messageID=9705196#9705196
    The proper way to design software is to start at the beginning and design Classes. Not try to butcher that which is working.
    You're running work outside the JVM and this work might interfere with other, similar work (the multi-threading issue.)
    I'd start with paper and pencil and see what conflicts might arise.

  • Things to consider while making a class singleton?

    sometimes i need to share the state of object across application.I get confused should i declare it singleton or declare state vaiables as static.
    As per mythoughts, if intention is just to share the state of object across application i should go for static variables. Is this right?
    My understanding about when we should go about singleton is below
    We should declare the class as singleton when we need only one instance across jvm. But i am not unable to find any practical scenario
    when we where we may need singleton . Any help here will be appreciated. Everywhere on different sites i get to see the example of logger
    class where the reason is generally given as so that single log file is created not multiple log files.
    But again this could have been achieved with declaring the file variable as static in logger file?
    So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
    which wont be possible if we make the separate instance of logger for each write..
    Is the above reasoning correct so that i can proceed in right direction?

    How will declaring its state as static accomplish that objective?With declaring variables as class variable instead of instance variables, there will be a single copy of each variable. In each instance (in this case logger if we dont declare it singleton) we can check if file is already created or not. I mean it will be visible across all instances.
    No, because the file name isn't the only state. There is also the output stream/writer, its current position, its charset, the log level, the logger name, its filters, its formatters, ...Agreed. I just wanted to convey the point. As you said there will be other parameters,in that case we can declare all of them as static.
    A configuration file holder is a good example: there is only one configuration file so there should only be one holder instance.Thanks for pointing it out. Configuration file is used mainly to read the properties. we usually dont update the values there.So even if we dont make it singleton it may be correct. The advantage i can think of making it singleton is that if configuration file is used frequently then we dont have create the object again and again.
    So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
    No it isn't, and that doesn't follow from anything you said previously so the 'so' part is meaningless.I want to say here is that t to have single log file should not be the only reason behind making the logger file as singleton, other reasons can be handling of concurrent writing too.
    Have a look at the Wikipedia article on the Singleton pattern, or buy the booki have gone through the singleton pattern in headfirst book and some of the articles on net. But they mainly describe how the make the class as singleton and the reason that We should declare the class as singleton when we need only one instance. But looking for actual scenarios where we need singleton. So i took the examplle of logger file which is used in many project and trying to understand it is constructed as singleton so that i can use in my project if required.
    Edited by: JavaFunda on Aug 28, 2011 3:51 AM
    Edited by: JavaFunda on Aug 28, 2011 3:56 AM

  • Does making more classes or incapsulation effect perfoemance?

    I have a Frame with a TabbedPane on it. There are 8 tabs. Each tab contains a JTable with lots of fields & 4 buttons.
    When I design all this stuff in JBuilder all panels are put into one class (...Frame class). I want to put every tab's JPanel into a separate class (... JPanel class). But some say that it might decrease otherall performance. It's sounds like a nonsense to me. But I'm not experienced programmer. And I'd like to make it clear for myself.
    One more thing. If I'm setting all class fields private & then write get/set, is the field access slower in this case than if I'm making all fields public?
    Can anyone help me? Does anyone know what does really decrease perfomance & what does not?

    ...but some say that it might decrease otherall performance
    Having more classes does increase the time it takes a program to run because of the additional class loading activity. Deciding whether to create another class is one of the toughest things in o-o design, and it rests on whether the extra load time is worth it for readability and reusability. The overall impact is not that large if you are talking about five or ten classes.
    If I'm setting all class fields private & then write get/set, is the field access slower in this case than if I'm making all fields public?
    Yes it is, but it is pretty negligible, especially if you are just returning a value. The real advantage of get/set is to allow for additional processing to take place when a property is modified or queried.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Making separate classes interact

    For an AI program I am making I need to get two programs interacting - I am doing this by using sockets and a threads.
    This program is a smaller version of th AI program. There are two of these programs - opposites i.e. where one says female the other says male and so on.
    Ok this is what should happen:
    -Program starts and background threads starts with it (always reading input).
    -Command is issued by the other program ("mate").
    -This triggers the connect() method which sends a command to the other program (action triggered) therefore they have interacted.
    Please give me any hints as to why this does not work.
    Thanks
    John
    import java.util.Scanner;
    import java.util.Vector;
    import java.util.Random;
    import java.io.*;
    import java.net.ConnectException;
    import java.net.ServerSocket;
    import java.net.Socket;
    //set path="C:\Program Files\Java\jdk1.5.0_08\bin"
    public class AIPetTest
         public Socket socket = null;
         public String command = "";
         public static Vector<String> commands = null;
         public String line = null;
         public String start()
              backgroundThread.start();
              Scanner command = new Scanner(System.in);
              String commandIssued = command.nextLine();
              if(commandIssued.equals("mate"))
                   try
                        connect("mate");
                   catch(Exception e)
                        System.err.println("Caught Exception: " + e.getMessage());
              return null;
         public void connect(String update) throws Exception
              System.out.println(update);
             try
                   System.out.println("Connection made");
                  socket = new Socket("localhost", 1977); // throws Exception below, if no connection is possible
             catch(ConnectException ce)
                  System.out.println("Connection lost");
                  socket = new ServerSocket(1977).accept();
                  // no connection was possible, so make app server
                  //socket = new ServerSocket(1977).accept();
                  // be aware that accept is blocking!
              command = commands.remove(0);  // Take the 1st object out
              System.out.println("Command: " + command);
              if(command.equals("updateMale")) // incoming
                   System.out.println("Mating");
              socket.getOutputStream().write(("updateFemale").getBytes());
              //socket.close();
        Thread backgroundThread = new Thread(new Runnable() // reads all incoming messages and stores them in a vector
             public void run()
                   System.out.println("Thread running");
                   commands = new Vector<String>();
                   try
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        while(true)
                              line = in.readLine();
                              if(line == null)
                                   break; // out of the while
                              commands.add(new String(line + '\n'));
                        in.close();
                   catch(IOException ioe)
                        System.err.println("Caught Exception: " + ioe.getMessage());
         public static void main(String[] args)
              AIPetTest pet = new AIPetTest();
              pet.start();
    }

    Both programs need to be a server and a client as
    they need to interact each way i.e. "mate" can be
    input in each program.
    A socket connection always has a server and a client. The client must always connect to the server.
    Once a connection exists you can send messages both ways.
    You could create two connections but that sounds like an unlikely scenario.
    I know a bit about socket programming in Java as I
    have made a remote admin tool before.
    I have to make each program always listen for
    commands - can you tell me if the thread does this?A socket either sends or gets messages. When it gets a message it does something. That has nothing to do with how the connection is established though.

  • Making my classes visible

    I have compiled a java applet with the WAR directory structure, I am however confused, as the WAR directory structure prohibits users from accessing files within a WEB-INF directory. Can you please tell me how to access theese files
    Thank you

    Not at all. Where exactly are you reading that?
    Your structure should look something like:
    .../webApplication
    .../webApplication/WEB-INF
    .../webApplication/WEB-INF/classes
    .../webApplication/WEB-INF/lib
    When a client makes a request for say
    http://yourDomain/appContextName/someFilePath
    the webserver will look for a file in
    .../webApplication/someFilePath.
    provided the someFilePath is not a secure directory (WEB-INF is).
    So you can put your applets anywhere under
    .../webApplication
    so long as they are not under WEB-INF.
    e.g., You could create a directory called
    .../webApplication/applets
    and put your applets in that directory.
    The WAR directory structure only specifies where you should put servlet-api-specific files. Applets have nothing to do with servlets and vice versa - they are just two Java technologies that happen to be used to build Web sites.

  • Re: Problem making a class property binable

    "Rahil Kidwai" <[email protected]> wrote in
    message
    news:gpc6h8$55e$[email protected]..
    > The following error is thrown on compilation if you make
    a property having
    > the
    > name similar to that of class.
    > 1046: Type was not found or was not a compile-time
    constant: Member
    >
    > public class Model
    > {
    > private var _member : Member;
    > public function get Member() : Member { return
    this._member; }
    > public function set Member( value : Member ) : void {
    this._member =
    > value; }
    > }
    >
    > Remedy is to use the fully qualified name for the class,
    like:
    >
    > public class Model
    > {
    > private var _member : Member;
    > public function get Member() : com.company.Member {
    return
    > this._member; }
    > public function set Member( value : com.company.Member )
    : void {
    > this._member = value; }
    > }
    >
    > But the same error will be reported if you now make this
    property
    > bindable.
    >
    > public class Model
    > {
    > private var _member : Member;
    > [Bindable]
    > public function get Member() : com.company.Member {
    return
    > this._member; }
    > public function set Member( value : com.company.Member )
    : void {
    > this._member = value; }
    > }
    >
    > Is there a workaround / solution to this problem. Am I
    missing something.
    > Also
    > changing the property name is not a possibility as it
    will roll into lot
    > of
    > changes in code base.
    There's a reason why the convention is to always use capital
    letters for
    starting class names and lowercase letters for properties.

    what kind of problem r u facing?
    plz highlight the code where u r facing the problem

  • Making a class more generic.

    Hi people. I have two classes as such:
    public class RelatedComponentCheckBox extends JCheckBox
            private List<JComponent> relatedComponents = null;
            public RelatedComponentCheckBox(String text, List<JComponent> relatedComponents)
                super(text);
                this.relatedComponents = relatedComponents;
            List<JComponent> getRelatedComponents()
                return relatedComponents;
        }and
    private class RelatedComponentComboBox extends JComboBox
            private List<JComponent> relatedComponents = null;
            public RelatedComponentCheckBox(String text, List<JComponent> relatedComponents)
                super(text);
                this.relatedComponents = relatedComponents;
            List<JComponent> getRelatedComponents()
                return relatedComponents;
        }I want all the behaviour of the check box and combo box in both cases and it works fine as it is. I was thinking that I didn't need two classes and could somehow use generics to cut it down to just one class. I have tried a few things but got nowhere.
    Is anybody able to help.???
    Thanks Boomah

    On a more general note, you might want to read up on "refactoring" once you decide how you want to re-organize the classes. There are a number of IDE's (e.g., [url http://www.eclipse.org]Eclipse) that eliminate most of the pain of refactoring.

  • Making a class immutable

    Ho w to make a class immutable??
    Thanx in advance

    Example
    import java.util.Date;
    * Planet is an immutable class, since there is no way to change
    * its state after construction.
    * @is.Immutable
    public final class Planet {
      public Planet (double aMass, String aName, Date aDateOfDiscovery) {
         fMass = aMass;
         fName = aName;
         //make a private copy of aDateOfDiscovery
         //this is the only way to keep the fDateOfDiscovery
         //field private, and shields this class from any changes
         //to the original aDateOfDiscovery object
         fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
      //gets but no sets, and no methods which change state
      public double getMass() {
        return fMass;
      public String getName() {
        return fName;
      * Returns a defensive copy of the field.
      * The caller of this method can do anything they want with the
      * returned Date object, without affecting the internals of this
      * class in any way.
      public Date getDateOfDiscovery() {
        return new Date(fDateOfDiscovery.getTime());
      // PRIVATE //
      * Primitive data is always immutable.
      private final double fMass;
      * An immutable object field. (String objects never change state.)
      private final String fName;
      * A mutable object field. In this case, the state of this mutable field
      * is to be changed only by this class. (In other cases, it makes perfect
      * sense to allow the state of a field to be changed outside the native
      * class; this is the case when a field acts as a "pointer" to an object
      * created elsewhere.)
      private final Date fDateOfDiscovery;

  • Difficulty Making Generic Class

    Hi. I've been attempting to make the following method generic:
    public static <E extends Comparable<E>> E readNumber(String prompt, String prompt2) {
            String input;
            char type; // necessary in order to select the correct methods and appease Eclipse
            int intRes;
            double dRes;
            type = readChar(prompt2);
            if (type == 'i' || type == 'I') {
                    try {
                            input = readString(prompt);
                            intRes = Integer.parseInt(input);
                    catch (Exception e) {
                            intRes = -1;
            } else if (type == 'd' || type == 'D') {
                    try {
                            input = readString(prompt);
                            dRes = Double.parseDouble(input);
                    catch (Exception e) {
                            dRes = -1;
            if (type == 'i' || type == 'I')
                    return intRes;
            else if (type == 'd' || type == 'D')
                    return dRes;
            return 0;
    }The readString method is as follows:
    public static String readString(String prompt) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = "";
            boolean done = false;
            while (!done) {
                    try {
                            if (prompt != null)
                                    System.out.print(prompt);
                            input = br.readLine();
                            if (input.length() > 0)
                                    done = true;
                    catch (Exception e) {
                            input = null;
            return input;
    }readChar is as follows:
    public static char readChar(String prompt) {
            String input;
            char result;
            try {
                    input = readString(prompt);
                    result = input.charAt(0);
            catch (Exception e) {
                    result = '0';
            return result;
    }All appropriate libraries (ie java.io.*) are included.
    Eclipses refuses to allow me to return either intRes or dRes (or, indeed, 0), since they can't be cast into E. If I set intRes and dRes as E, then I can't use the Integer and Double methods.
    Can this be made generic, or will I have to keep creating new methods for each primitive type?
    Edited by: KBKarma on May 11, 2008 6:06 AM
    ... Didn't notice the Preview tab. So sorry.

    KBKarma wrote:
    However, in the main class, I initialised an integer variable one with the line readNumber("Enter an integer: " , 'i').intValue(). Eclipse brought up the following error:
    "Bound mismatch: The generic method readNumber(String, char) of type Input is not applicable for
    the arguments (String, char). The inferred type Comparable<Comparable<E>> is not a valid
    substitute for the bounded parameter <E extends Comparable<E>>"So I assume, the code for readNumber above is incorrect, as the invoked method here takes a char as second parameter and no String.
    The main problem is that the compiler tries to infer the type of the return value from whatever its context is, and it obiously fails to do so. It's difficult to say why, without seeing the actual call including variable type definitions etc.

  • Deck Class, array out of bounds

    I keep getting an "array out of bounds" exception when I run the program. I tried to make the array 666666 instead of just 52 and i still get that error. HELP!! ,
    IM ONLY HAVING PROBLEMS WITH THE SHUFFLE METHOD
    By the way, this time i REALLY cleaned up the class and It compliles correctly so it would help if you guys that posted last time would take a look at it again.
    (and I know that the name of the class shoudl be card or something but MY teacher wanted it to be deck)
    Any help greatly appreciated and if you see any other errors in logic or code please tell me!
    this is the testing class im using
    public class DeckTester{
         public static void main ( String[] args ){
              Deck[] decko = Deck.makeDeck();
              Deck.printDeck( decko );
              System.out.println(" ");
              Deck.printFirstFive(decko);
              Deck[] newDeck = new Deck[66666]; // tried to make this big because i keep getting array out of bounds error
              newDeck = Deck.shuffleDeck( decko );
              Deck.printDeck ( newDeck );
    }and this is the deck class
    import java.lang.Math;
    class Deck
         int suit, rank;
    /////////////////////////////////////////// CONSTRUCTORS
      public Deck () {
        this.suit = 0;  this.rank = 0;
      public Deck (int suit, int rank) {
        this.suit = suit;  this.rank = rank;
    /////////////////////////////////////////// PRINT CARD
      public static void printCard( Deck c ){
           String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
         String[] ranks = { "narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
           System.out.println (ranks[c.rank] + " of " + suits[c.suit]);
      }//end method
    ////////////////////////////////////////// CREAT NEW DECK
      public static Deck[] makeDeck(){
           int index = 0;
        Deck[] deck = new Deck [52];
        for (int suit = 0; suit <= 3; suit++) {
               for (int rank = 1; rank <= 13; rank++) {
                     deck[index] = new Deck (suit, rank);
                 index++;
      return deck;
      }//end method
    /////////////////////////////////////////// PRINT DECK
      public static void printDeck (Deck[] deck) {
        for (int i=0; i<deck.length; i++) {
          printCard (deck);
    /////////////////////////////////////////// PRINT FIRST 5
    public static void printFirstFive (Deck[] deck){
         int x = -1;
         while (x != 4 ){
              x += 1;
              printCard(deck[x]);
    /////////////////////////////////////////// SHUFFLE
    // this is supposed to simulate real riffle shuffling
    public static Deck[] shuffleDeck (Deck[] deck){
         //creating and initializing variables
         int cut = (int)(22+ Math.random() * 8); //cut the deck into 2 parts
         int side1 = cut; //how many cards in first side
         int side2 = 52 - cut; //how many in second
         int numberCards = 0, neg_to_pos = -1, k = 0; //how many cards go down from each side
         int x = -1, y = side1, z = 0, d = 0; //begining point of first and second halves
         Deck[] shuffledDeck = new Deck [66666]; //the shuffled deck goes into this one
    /* ^^^^^^^^^^^^^^^ INITIALIZING VARIABLES ^^^^^^^^^^^^^^^^^^ */
         while ( k < 100 ){
              k += 1; // i used 100 for now because you can
              neg_to_pos *= (-1); //switches which hand half of the deck you take cards form
              numberCards = numberCard();     
         if ( neg_to_pos == 1) { // this is the first half
              if ( x < (side1 + 1) ){ // checks to see if first half is empty
                   //for( x = x; x <= numberCards /*go untill variable*/; ++x ) {
                        z = (-1); // checks if you put down all the "numberCards"
                        while ( x <= numberCards ) {     
                             z += 1;
                             x += 1; // x is which spot in the deck the cards go
                             shuffledDeck[x] = deck[x];     
                        }//end for     
                   }//end if
         }//end if
         if ( neg_to_pos == (-1) ) { // this is the second half
              if ( x <= 52 ){
                   //for( y = y; y < numberCards; y++ ) {
                   d = (-1);
                   while ( d <= numberCards ) {
                        d += 1;
                        y += 1;     
                        shuffledDeck[y] = deck[y];
                   }//end for
              }//end if
         }//end if (else)
    }// end while
    return shuffledDeck;
    }//end shuffle method
    /////////////////////////////////////////// NUMBER CARDS
         private static int numberCard() {
              /*numberCards is how many cards you take put down
              from each hand. In shuffling it is not always the
              same number, so this picks waht that number is */
              int percent = (int)(Math.random() * 99);
              int numberCards = 0;
              if (percent < 20) {
                   numberCards = 1;}
              else if( percent >= 20 && percent <= 49 ){
                   numberCards = 2;}
         else if( percent >= 50 && percent <=69 ){
              numberCards = 3;}
         else if( percent >= 70 && percent <=79 ){
              numberCards = 4;}
         else if( percent >= 80 && percent <=84 ){
              numberCards = 5;}
         else if( percent >= 85 && percent <=89 ){
              numberCards = 6;}
         else if( percent >= 90 && percent <=92 ){
              numberCards = 7;}
         else if( percent >= 93 && percent <=95 ){
              numberCards = 8;}
         else if( percent >= 96 && percent <=97 ){
              numberCards = 9;}
         else{ numberCards = 10; }
         return numberCards;
         }//end numberCards METHOD
    /////////////////////////////////////////// END CLASS
    }//end class      
    /////////////////////////////////////////// END     

    Wooo, you;ve made this far to complicated. Lets start with a class called Card, let just imagine this exists, we won;t go into any more detail. Now lets look at a class called Deck, which has a collection of cards.
    class Deck {
      private java.util.Vector cards = new java.util.Vector();
      Deck() {
          for (int i = 0; i < 52, i++) {
           cards.add(new Card(i));
      } //this method adds 52 cards to the vector
      public Card getCardAt(i) {
         return (Card) cards.removeElementAt(i); //can't remember exact method
      public Card getRandomCard() {
         int index = Random.nextInt() * 52;
          return getCardAt(index);
      public int getSize() {
         return cards.size();
    }Okay, this method has 52 cards and you can either get one at the specificed index or get a random card. Because the cards are removed when they are returned you will never get the same card twice. There is no point in shuffling them if you just return a random card ;)
    Okay, now all you need when using the deck class is to create a new instance for each new game:
    void deal(Player[] players) {
      Deck d = new Deck();
       while (d.getSize() > players.length) {
           for (int i = 0; i < players.length; i++) {
                     players.dealCard(d.getRandomCard()());
    Always remember the KISS process:
    Keep It Simple, Stupid :)

  • Help with sorting a deck class

    I am using this from a card class...and am trying to sort the cards in numeric order, but keep getting errors
    public class Deck
    private int top;
    private int count;
    private int deckSize;
    Card [] cards=new Card[53];
    public Deck()
    for (int x=0; x<cards.length; x++)
    cards[x]=new Card();
    deckSize++;
    for (int z=0; z<cards.length; z++)
    for (int x=0; x<4; x++)
    if(cards[z].suit==x)
    for (int y=1; y>14; y++)
    if (cards[z].value==y)
    int cardLen=cards.length;
    Card temp=new Card(cards[z.suit],cards[z.value]);
    cards[z]=cards[cardLen-z-1];
    cards[cardLen-z-1]=temp;
    }

    tjacobs01 wrote:
    Create a java.util.Comparator for your cards, and then use Arrays/Collections.sortArr, ye mateys! Swap the deck!

  • Using a variable from one class in another

    For learning purposes, I thought I'd have a stab at making a role-playing RPG.
    The first class I made was the Player class;
    public class Player
         public static void main(String[] args)
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public static String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public static void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public static void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public static void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public static void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public static void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public static void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public static void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
    }And that would be used in the Play class;
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }     But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
    public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
    I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
    Edited by: xcd on Jan 6, 2010 8:12 AM
    Edited by: xcd on Jan 6, 2010 8:12 AM

    HI XCD ,
    what about making Player class as
    public class Player
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
         }and Play class
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
    Hope it help :)

  • JVM crash when adding method to class

    Hello,
    I am getting some kind of problem with the virtual machine. The JVM crashes when making a class (with new). It happened when I was adding some functionality to the class, I worked my way backwards and discovered it crashes when I add any new methods, if I comment them out again everything works, adding a method by any name causes to crash.
    I went in debug to find out where it was happening, and it happens on this line:
    public PerspectiveActionToolBarHeader createPerspectiveActionToolBarHeader() {
         PerspectiveActionToolBarHeader ret = null;
         ret = new PerspectiveActionToolBarHeader(this); // << here
         return ret;
    }The PerspectiveActionToolBarHeader is the class where adding methods causes it to fail. For example, it has the method
    public Container getContainer() {
         return this;
    }and works, but if I add:
    public void anything(){} it causes a crash on the new PerspectiveActionToolBarHeader(this);
    When stepped into with the debugger it goes to the (source not found) ClassNotFoundException and eventually before the crash the (stack?) looks like this:
    Launcher$AppClassLoader(ClassLoader).loadClass(String) line: not available     
    MaldiSoftwareOptionsUIEnsemble(PerspectiveUIEnsemble).createPerspectiveActionToolBarHeader() line: 72
    and the debugger describes the class just before the crash:
    Launcher$AppClassLoader (id=44)     
    arg0     "saiman.uiobjnew.PerspectiveToolBarButton" (id=51) << has just changed
    and the log file (not sure how much to copy here!):
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_ILLEGAL_INSTRUCTION (0xc000001d) at pc=0x005c0001, pid=15504, tid=20112
    # JRE version: 6.0_24-b07
    # Java VM: Java HotSpot(TM) Client VM (19.1-b02 mixed mode windows-x86 )
    # Problematic frame:
    # C 0x005c0001
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    --------------- T H R E A D ---------------
    Current thread (0x011ca000): JavaThread "main" [_thread_in_vm, id=20112, stack(0x01140000,0x01190000)]
    siginfo: ExceptionCode=0xc000001d
    Registers:
    EAX=0x13e13248, EBX=0x6da0daa8, ECX=0x13e13250, EDX=0x13e131f8
    ESP=0x0118f93c, EBP=0x0118f9a0, ESI=0x011ca9b0, EDI=0x011ca9ac
    EIP=0x005c0001, EFLAGS=0x00010206
    Register to memory mapping:
    EAX=0x13e13248
    {method}
    - klass: {other class}
    EBX=0x6da0daa8
    0x6da0daa8 is pointing to unknown location
    ECX=0x13e13250
    {method}
    - klass: {other class}
    EDX=0x13e131f8
    {constMethod}
    - klass: {other class}
    - method: 0x13e13248 {method} 'flipVisible' '(I)V' in 'saiman/uiobjnew/PerspectiveActionToolBarHeader'
    - exceptions: 0x13bf11e8
    ESP=0x0118f93c
    0x0118f93c is pointing into the stack for thread: 0x011ca000
    "main" prio=6 tid=0x011ca000 nid=0x4e90 runnable [0x0118f000]
    java.lang.Thread.State: RUNNABLE
    EBP=0x0118f9a0
    0x0118f9a0 is pointing into the stack for thread: 0x011ca000
    "main" prio=6 tid=0x011ca000 nid=0x4e90 runnable [0x0118f000]
    java.lang.Thread.State: RUNNABLE
    ESI=0x011ca9b0
    0x011ca9b0 is pointing to unknown location
    EDI=0x011ca9ac
    0x011ca9ac is pointing to unknown location
    Top of Stack: (sp=0x0118f93c)
    0x0118f93c: 6d94272d 011ca370 13e17d40 011ca000
    0x0118f94c: 011ca000 01a30950 011ca748 011ca9b4
    0x0118f95c: 011cab3c 0118fb28 011c6748 011ca348
    0x0118f96c: 011ca370 011ca73c 6da0daa8 011ca350
    0x0118f97c: 011ca370 0118f9cc 011ca9a8 0118f9c8
    0x0118f98c: 011ca788 011ca370 011ca9b0 011ca000
    0x0118f99c: 13e17d40 0118f9cc 6d943009 00000910
    0x0118f9ac: 011ca9ac 00000001 011ca000 011ca000
    Instructions: (pc=0x005c0001)
    0x005bfff1: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ff
    0x005c0001: ff ff 7f 00 00 00 00 00 00 00 00 ff ff ff ff 00
    Stack: [0x01140000,0x01190000], sp=0x0118f93c, free space=318k
    Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
    C 0x005c0001
    V [jvm.dll+0x153009]
    V [jvm.dll+0xdecdb]
    V [jvm.dll+0xe1887]
    V [jvm.dll+0xe1c46]
    V [jvm.dll+0xec09a]
    j saiman.uiobjnew.PerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+2
    j saiman.mv.ModelViewPerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.addButtons()V+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+21
    j saiman.mv.ModelViewPerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.uiobjnew.SoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.wmaldi.MaldiSoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.newuiimpl.MassSpectrumMainFrameImpl.main([Ljava/lang/String;)V+173
    v ~StubRoutines::call_stub
    V [jvm.dll+0xf0ab9]
    V [jvm.dll+0x1837d1]
    V [jvm.dll+0xf0b3d]
    V [jvm.dll+0xfa0d6]
    V [jvm.dll+0x101cde]
    C [javaw.exe+0x2155]
    C [javaw.exe+0x8614]
    C [kernel32.dll+0x51194]
    C [ntdll.dll+0x5b3f5]
    C [ntdll.dll+0x5b3c8]
    Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
    j saiman.uiobjnew.PerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+2
    j saiman.mv.ModelViewPerspectiveUIEnsemble.createPerspectiveActionToolBarHeader()Lsaiman/uiobjnew/PerspectiveActionToolBarHeader;+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.addButtons()V+1
    j saiman.uiobjnew.PerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+21
    j saiman.mv.ModelViewPerspectiveUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.uiobjnew.SoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.wmaldi.MaldiSoftwareOptionsUIEnsemble.<init>(Lsaiman/uiobjnew/MultiPerspectiveFrame;)V+2
    j saiman.newuiimpl.MassSpectrumMainFrameImpl.main([Ljava/lang/String;)V+173
    v ~StubRoutines::call_stub
    --------------- P R O C E S S ---------------
    Java Threads: ( => current thread )
    0x01b05400 JavaThread "AWT-Windows" daemon [_thread_in_native, id=19680, stack(0x18560000,0x185b0000)]
    0x01b04800 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=19516, stack(0x18140000,0x18190000)]
    0x01b04000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=20064, stack(0x18040000,0x18090000)]
    0x01b03c00 JavaThread "CompilerThread0" daemon [_thread_blocked, id=20276, stack(0x17ff0000,0x18040000)]
    0x01aeb000 JavaThread "JDWP Command Reader" daemon [_thread_in_native, id=16832, stack(0x17fa0000,0x17ff0000)]
    0x01aea000 JavaThread "JDWP Event Helper Thread" daemon [_thread_blocked, id=16360, stack(0x17ef0000,0x17f40000)]
    0x01ae8000 JavaThread "JDWP Transport Listener: dt_socket" daemon [_thread_blocked, id=20084, stack(0x17ea0000,0x17ef0000)]
    0x01ade400 JavaThread "Attach Listener" daemon [_thread_blocked, id=19772, stack(0x17d90000,0x17de0000)]
    0x01add400 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=20192, stack(0x17d40000,0x17d90000)]
    0x01ab2800 JavaThread "Finalizer" daemon [_thread_blocked, id=17344, stack(0x17cf0000,0x17d40000)]
    0x01aabc00 JavaThread "Reference Handler" daemon [_thread_blocked, id=19964, stack(0x17ca0000,0x17cf0000)]
    =>0x011ca000 JavaThread "main" [_thread_in_vm, id=20112, stack(0x01140000,0x01190000)]
    Other Threads:
    0x01aa7c00 VMThread [stack: 0x011d0000,0x01220000] [id=19144]
    0x01b17400 WatcherThread [stack: 0x180f0000,0x18140000] [id=12792]
    VM state:not at safepoint (normal execution)
    VM Mutex/Monitor currently owned by a thread: None
    Heap
    def new generation total 4928K, used 768K [0x03bf0000, 0x04140000, 0x09140000)
    eden space 4416K, 5% used [0x03bf0000, 0x03c30380, 0x04040000)
    from space 512K, 100% used [0x040c0000, 0x04140000, 0x04140000)
    to space 512K, 0% used [0x04040000, 0x04040000, 0x040c0000)
    tenured generation total 10944K, used 1858K [0x09140000, 0x09bf0000, 0x13bf0000)
    the space 10944K, 16% used [0x09140000, 0x09310948, 0x09310a00, 0x09bf0000)
    compacting perm gen total 12288K, used 9598K [0x13bf0000, 0x147f0000, 0x17bf0000)
    the space 12288K, 78% used [0x13bf0000, 0x1454fb70, 0x1454fc00, 0x147f0000)
    No shared spaces configured.
    Edited by: hanvyj on 07-Jun-2011 02:39
    Edited by: hanvyj on 07-Jun-2011 02:43

    I think I may have stumbled across the answer, It seems that the abstract class PerspectiveToolBar implements
    the interface with the method public Container getContainer() but does not declare it, this should be fine because the method is abstract but it crashes. When I add the method public abstract Container getContainer(); to the abstract sub-class there is no error. I'm going to try make a small compilable example to see if I can reproduce it.
    edit its actually only one of the two interface methods, and not getContainer(), but another one. If anyone is interested here is the interface:
    public interface IMassSpectrometerPassableControlContainer
         Container getContainer();
         void reloadWidgetsOnVisible(boolean visible);
    }and it works only if there is "public abstract void reloadWidgetsOnVisible(boolean visible);" in the abstract class PerspectiveToolBar implementing IMassSpectrometerPassableControlContainer.
    I tried to reproduce it, but I can't get another class to repeat the behaviour, so I don't think I can post a bug report on it. Here is my attempt anyway:
    import javax.swing.JToolBar;
    * Class     Test.java
    * Date:     7 Jun 2011
    * @author     tofuser
    public class Test extends Subclass
         public static void main(String args[])
              System.out.println("in main method");
              Test t = new Test();
              t.interfaceMethod();
         @Override
         public void interfaceMethod()
              System.out.println("interface method");
    abstract class Subclass extends JToolBar implements Interface
         private static final long serialVersionUID = 1L;
         //this line is where it breaks in my code, including it works
         //public abstract void interfaceMethod();
    interface Interface
         public abstract void interfaceMethod();
    }Edited by: hanvyj on 07-Jun-2011 03:56

  • Purpose of static classes

    What is the purpose of making a class static?
    public static class December {
    }The only reason I can see is to access inner-classes without instantiating the outer-class? Are there any other?

    see these
    http://forum.java.sun.com/thread.jsp?forum=31&thread=277820
    http://forum.java.sun.com/thread.jsp?forum=31&thread=305260

Maybe you are looking for

  • How can I boot a linux live cd in my macbook pro 8,1

    I have a macbook pro 8,1 13inch. Whenever I attempt to boot from a linux live cd (ubuntu, kubuntu, gparted, knoppix) I get dropped to a busybox interface with a message that the live file system can not be found. I have tested the linux cd on a non a

  • Error: (F5 263) The difference is too large for clearing in  EBS

    Hi i was running  FF_5 , i got the the below error. Error: (F5 263) The difference is too large for clearing The next detail screen i found that the Bank account posting gone correct but issues in subledger posting (there 27 errors in the table). Can

  • Order Status says "Page Currently Not Available"

    It has been working for me ever since Thursday. It hasn't said anything but We Received Your Order and We Are Processing it or whatever, but at least it came up. Is it down for everyone else?

  • Nokia 3210 firmware Upgrade

    Hi, I need for professional use to upgrade a 3210 phone to the last firmware. Do you know where I can found the last firmware ? And where a I can found the cable and software to make the upgrade ? (I allready try to go in a Nokia fist level shop, but

  • How do I create a film projector effect?

    I have some text in photoshop and I want it to appear as if it's being projected from behind. So I want to create a blurry skewed version of the text behind it.  Anyone have any suggestions on how to achieve this?I tried just blurring it and using th