Ideas for making code faster?

OK, I'm tryig to make a random move generator for a chess game. I want the move to be legit. It's kind of a first step to making an AI I guess. It works but unfortunately it brings my system to it's knees, and my system is pretty good. Here's the generator, any help would be appreciated.
Basically it makes a very large Vector of objects that contain all of the valid moves, then picks one at random.
import java.util.Vector;
public class MoveGenerator
     int team, currentX, currentY, r;
     int[] randomMove = new int[4];
     Vector TeamMoves = new Vector();
     // Creates a new MoveGenerator which will play for team tm
     public MoveGenerator(int tm){
          team = tm;
     // Gets all the possible moves for a team during at a given time and places
     // each move into Vector TeamMoves
     public Vector getTeamMoves(){          
          for (int row = 0; row < 8; row++){
               for (int col = 0; col < 8; col++){
                    // Gets the valid moves for each piece
                    if (ChessBoard.cbLayout[col][row] != null){                         
                         if (ChessBoard.cbLayout[col][row].getTeam() == team){
                              //set currentX/Y to position of each piece
                              currentX = ChessBoard.cbLayout[col][row].getPosition()[0];
                              currentY = ChessBoard.cbLayout[col][row].getPosition()[1];
                              // Goes through and checks if each square is a valid move
                              // for this piece and if it is adds it to TeamMoves
                              for (int y = 0; y < 8; y++){
                                   for (int x = 0; x < 8; x++){                                   
                                        if (ChessBoard.cbLayout[col][row].getValidMoves()[x][y]){
                                             TeamMoves.addElement(new MoveValues(currentX, currentY, x, y));
          return TeamMoves;
     // Sets new random number
     public int renewSeed()
          r = (int) (Math.random() * getTeamMoves().size());
          return r;
     // Will choose one of the valid moves at random
     public int[] getMove(){          
          System.out.println(r);
          randomMove[0] = ((MoveValues)(getTeamMoves().elementAt(r))).getMoveValues()[0];
          randomMove[1] = ((MoveValues)(getTeamMoves().elementAt(r))).getMoveValues()[1];
          randomMove[2] = ((MoveValues)(getTeamMoves().elementAt(r))).getMoveValues()[2];
          randomMove[3] = ((MoveValues)(getTeamMoves().elementAt(r))).getMoveValues()[3];          
          return randomMove;
     // Used to store movement info, all possible moves are then added to
     // Vector TeamMoves. Of which one will be chosen at random.
     class MoveValues
          int fromX, fromY, toX, toY;
          int[] moveArray = new int[4];
          // Sets up an obfject storing the values for a move
          public MoveValues(int x1, int y1, int x2, int y2){
               fromX = x1;
               fromY = y1;
               toX = x2;
               toY = y2;
          // Retrieves the values of the move in this object
          public int[] getMoveValues(){
               moveArray[0] = fromX;
               moveArray[1] = fromY;
               moveArray[2] = toX;
               moveArray[3] = toY;
               return moveArray;
}

Here's a really quick stab at some really simple optimizations...
public Vector getTeamMoves(){
List     listMoves = new ArrayList();          // OPTIMIZE -- use ArrayList instead of Vector
          for (int row = 0; row < 8; row++){
               for (int col = 0; col < 8; col++){
                    // Gets the valid moves for each piece
               ?ChessBoardLayout? layout = ChessBoard.cbLayout[col][row]; // OPTIMIZE - dereference object once
                    if (layout != null){                         
                         if (layout.getTeam() == team){
                              //set currentX/Y to position of each piece
                              int moves[] = layout.getPosition(); // OPTIMIZE- Call method ONCE
                              currentX = moves[0];
                              currentY = moves[1];
                              // Goes through and checks if each square is a valid move
                              // for this piece and if it is adds it to TeamMoves
                              int validMoves[][] = layout.getValidMoves(); // OPTIMIZE- Move method call outside loops
                              for (int y = 0; y < 8; y++){
                                   for (int x = 0; x < 8; x++){                                   
                                        if (validMoves[x][y]){
                                             listMoves.add(new MoveValues(currentX, currentY, x, y));
          return new Vector(listMoves);
     }

Similar Messages

  • Making code faster smaller and more elegant

    hi just like yesterday I�m new to java. first of all I want to get familiar with the basics. I wrote a little game therefore. with some help. within the code are no mistakes, compiling errors or such. but now my question is why is my CPU usage nearly 75% when I run it. when the �h� ( Thread.sleep(h); ) is about 5 which makes the game faster but the CPU usage is 100%. Are there any possibilities to make the code faster? next question. are there any tricks to make the code more elegant or smaller? you know what I mean? it�s quite difficult for me to express what I want cause my English isn�t the best�
    what ever here is the code
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class BricksGame extends JFrame implements MouseListener, MouseMotionListener{
         private int mouseX, mouseY;
         double a = -3;
         int delta = 1;
         int beta = -3;
         int x_max = 288;
         int y_max = 320;
         int x_min = 0;
         int y_min = 0;          
         int x = 5;
         int y = 5;
         int b = y_max;
         int h = 15;
         int y_block = 80;
         int i;
         int x_point;
         int y_point =0;
         int punkte = 0;
         double k ;
         double r;
         int zahl = 1;
         boolean changed = true;     
         boolean gameNotOver = true;
         JPanel panelOben = new MyPanel();
         JPanel panelUnten = new JPanel();
         JLabel labelU1 = new JLabel();
         JLabel labelU2 = new JLabel("Punktestand: 0");
           JButton b1 = new JButton("restart");
         public  BricksGame(){
              setSize(400,600);
              setLocation(100,200);
              Dimension full = getSize();
              mouseX = full.width/2;
              mouseY = full.height/2;
              addMouseMotionListener(this);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {System.exit(0);}
              panelOben.setLayout(null);
              //Ausrichtung der Elemente
              panelOben.setBounds(50, 50, 400, 500);
              panelUnten.addMouseMotionListener(this);
              panelUnten.setLayout(null);
                   //Ausrichtung der Elemente
              panelUnten.setSize(300, 100);          
              panelUnten.setBounds(50, 500, 300, 100);
              labelU1.setBounds(100,380,130,25);
              labelU2.setBounds(150,430,130,25);
              b1.setBounds(150,500, 80, 30);
              b1.addMouseListener(this);
              ImageIcon ii2 = new ImageIcon(getClass().getResource("TW1.gif"));
              labelU1.setIcon(ii2);
                   //Hinzuf�gen der Elemente
              panelUnten.add(labelU1);
              panelUnten.add(labelU2);
              panelUnten.add(b1);
              getContentPane().add(panelOben);
              getContentPane().add(panelUnten);
              setResizable(false);
              (new Mover()).start();
              setVisible(true);          
              validate();     
         public static void main (String[]args){
              BricksGame object = new BricksGame();     
         public void mousePressed (MouseEvent e) {}
         public void mouseReleased (MouseEvent e) {}
         public void mouseClicked (MouseEvent e) {
              restart();
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited (MouseEvent e) {}
         public void mouseDragged (MouseEvent e) { }
         public void mouseMoved (MouseEvent e) {
              mouseX = e.getX();
              if (mouseX <= 85){
                   mouseX = 85;
              }else if (mouseX >= 319){
                   mouseX = 319;
              labelU1.setBounds(mouseX -35 ,380,70,25);
          * @author Haferberger
          * To change the template for this generated type comment go to
          * Window>Preferences>Java>Code Generation>Code and Comments
         class Mover extends Thread{
              public void run(){
                   while (gameNotOver){
                        try {Thread.sleep(h);}
                        catch (Exception e) {
    //                     TODO: handle exception
                        repaint();
          * @author Haferberger
          * To change the template for this generated type comment go to
          * Window>Preferences>Java>Code Generation>Code and Comments
         class MyPanel extends JPanel{
              public void paint(Graphics g){
                   if (y <= y_min && !changed){
    //                    System.out.println("up");     
                        //wie oft oben gegen     
                        i++;
                        //Koordinaten des G�nen Punktes
                        x_point =x_max -x;
                        y_point =0;
                        //Nach 5 mal oben gegen wird der Winkel ge�ndert
                        if (i%5==0){
                             zZahl();
                             alpha();
                        //Richtungs�nderung
                        a = -a;
                        b = (int)(y_min - a*x);
                        changed = true;     
                   }else if (y >= y_max && !changed){
    //                    System.out.println("down");                    
                        //Bei Ber�hrung unten wird der Block verschoben
                        if (y_block == 221){
                             beta = -beta;
                        }else if (y_block == 80){
                             beta = -beta;
                        y_block+= beta;
                        //Betimmen wo der Ball aufkommt
                        if (x + 5 >= mouseX - 84 && x + 5 <= mouseX -27 ){
    //                         System.out.println("Mitte");
                        }else if(x + 5 >= mouseX - 95 && x + 5 <= mouseX -85 ){
    //                         System.out.println("au�en links");
                             if(delta > 0){
                                  delta = -delta;
                                  a = -a;
                                  b = (int)(y_min - a*x);
                        }else if(x + 5 <= mouseX -16 && x + 5 >= mouseX -26 ){
    //                         System.out.println("au�en rechts");
                             if(delta < 0){
                                  delta = -delta;
                                  a = -a;
                                  b =(int)(y_min - a*x);
                        }else{
                             System.out.println("daneben");
                             gameNotOver=false;
                             a = -a;
                             b = (int)(y_max - a*x);
                        changed = true;
                   }else if (x >= x_max && !changed){
    //                    System.out.println("right");                                        
                        a = -a;
                        b = (int)(y - a*x_max);
                        delta = -delta;
                        changed = true;
                   }else if (x <= x_min && !changed){
    //                    System.out.println("left");
                        a = -a;
                        b = (int)(y - a*x_min);
                        delta = -delta;
                        changed = true;               
                   }else if (y == y_block && x>72 && x<216 && !changed){
    //                    System.out.println("Balken unten");
                        a = -a;
                        b = (int)(y - a*x);
                        changed = true;               
                   }else if (y == y_block+20 && x>72 && x<216 && !changed){
    //                    System.out.println("Balken oben");
                        a = -a;
                        b = (int)(y - a*x);
                        changed = true;               
                   }else{
                        changed = false;                    
                   g.setColor(Color.cyan);
                   g.fillRect(0, 0, 300, 330);
                   x+= delta;               
                   y = (int)(a*x + b);
                   g.setColor(Color.red);               
                   g.fillOval(x,y+5,10,10);
                   g.setColor(Color.magenta);
                   g.fillRect(72, y_block,144,20);
                   y_point+=2;
                   if(y_point==310){
                        y_point=500;
                        if(x_point + 5 >= mouseX - 94 && x_point + 5 <= mouseX -20 ){
                             punkte+=50;
                   g.setColor(Color.green);               
                   g.fillOval(x_point,y_point,20,20);
                   labelU2.setText("Punktestand: " + punkte);
                   labelU2.validate();
         public void zZahl(){
                   r = (Math.random() * 10);
                   zahl = (int)r%5 + 1;
         public void alpha(){
              switch(zahl){
                   case 4:
                        if (a<0){
                             a=-1;
                        }else if (a>0){
                             a=1;
                        if (delta<0){
                             delta=-4;
                        }else if (delta>0){
                             delta=4;
                        break;
                   case 3:
                        if (a<0){
                             a=-2;
                        }else if(a>0){
                             a=2;
                        if (delta<0){
                             delta=-4;
                        }else if(delta>0){
                             delta=4;
                        break;
                   case 5:
                        if (a<0){
                             a=-3;
                        }else if (a>0){
                             a=3;
                        if (delta<0){
                             delta=-1;
                        }else if (delta>0){
                             delta=1;
                        break;
                   case 2:
                        if (a<0){
                             a=-0.5;
                        }else if (a>0){
                             a=0.5;
                        if (delta<0){
                             delta=-4;
                        }else if (delta>0){
                             delta=4;
                        break;
                   case 1:
                        if (a<0){
                             a=-0.2;
                        }else if (a>0){
                             a=0.2;
                        if (delta<0){
                             delta=-5;
                        }else if (delta>0){
                             delta=5;
                        break;
         public void restart(){
              gameNotOver=true;
              y_block=80;
              beta = -3;
              x=mouseX;
              (new Mover()).start();
              punkte = 0;
              labelU2.validate();
    }thanks

    First of all, big friendly advice: split your code into few classes and methods. Currently your code looks very ugly.
    And one simple question: what is happening with Mover instance after restart? I don't see anything that stops old Mover thread instance before starting a new one...
    And so on...
    It is much simpler to answer your question when code is splited in small parts - problems then are located in small pieces of code.

  • Gava SE 1.0, a Java IDE for international code,  released,

    Please go to check http://www.gavasoft.com for more information
    Gava is a Java Integrated Development Environment (IDE), built in pure Java, to develop Java applications and applets. Most part of Gava is developed in Gava itself. As a pure Java application, Gava can run on both Windows and Unix/Linux platforms. It requires JRE 1.4 to execute, but it can debug JDK1.2, 1.3, and 1.4.
    Intuitive, fast, and powerful. Gava is a fast IDE built with many unique and well-thought-out optimizations. Gava users will enjoy a smooth coding feeling throughout the development phases - fast start-up, fast code completion, fast compiling, etc. With a relatively simple but intuitive GUI, Gava provides users powerful functionalities. It suits the needs of all developers, from entry-level to advanced.
    Internationalization. Gava is an IDE designed for developing international Java applications. First, Gava itself is a multilingual Java application. Developers can set Gava to any language, no matter what OS (localized or English version) it is running on. Second, Gava provides many functionalities and tools to easily develop multilingual applications, with either localization or internationalization technologies.
    Write once, develop anywhere. With Gava, you can not only run your projects on multi-platforms, you can also develop your projects on multi-platforms. Gava implements an OS-independent project management architecture. Based on this architecture and other special features in Gava, developers can easily port Gava's projects to different platforms, file systems, or file directories.
    Multiple debugging sessions. Gava can debug multiple debuggees within the same running instance of Gava. This feature makes Client Server debugging much easier, Gava users don't have to switch between running applications.
    Customizable. Gava is configurable. Gava users can customize the GUI look and feel with their favorable fonts and colors to create a work environment suitable for different occasions, either for demonstration or development.
    Now Gava SE 1.0 is available for download. We would appreciate any and all feedback regarding the product. You may download a fully funtional 30 days trial version from our download page, and try it to see how you like it. Thank you.

    As if we don't have enough IDE's already??? And what's this?
    ...Most part of Gava is developed in Gava itself...Huh? is Gava a language too? Like we need yet another language?

  • Using 'personal hotspot' successfully - any ideas for making it work?

    I signed up for a 'personal hotspot' on my Verizon iPhone4 months ago but find that it rarely works.  Have others been able to make it work?  Any ideas on how I can use it successfully?  I am using it in New York City.

    http://support.apple.com/kb/TS2756

  • Idea for this code pls

    Hi,
    In the below code, I have certain doubts.
    1.Do I need to go for inner join statements in fetching data for parameters?..
    2. How can I group by document type and print the total of net value...for this do i need to move the datas to another internal table ?..How to ?
    tables : vbak,vbap.
    data : begin of itab occurs 0,
            vbeln like vbak-vbeln,
            auart like vbak-auart,
            netwr like vbak-netwr,
            waerk like vbak-waerk,
            zmeng like vbap-zmeng,
            zieme like vbap-zieme,
            posnr like vbap-posnr,
            matnr like vbap-matnr,
            end of itab.
    select-options : s_vbeln for vbak-vbeln.
    Parameters     : s_vkorg(10) type c,
                     s_vtweg(10) type c,
                     s_spart(10) type c.
    start-of-selection.
    select avbeln aauart anetwr awaerk bzmeng bzieme bposnr bmatnr
    into table itab from vbak as a inner join vbap as b on b~vbeln =
    avbeln where avbeln in s_vbeln .
    loop at itab.
    write : /5 itab-vbeln,15 itab-posnr,25 itab-auart,
    30 itab-matnr,35 itab-zmeng,40 itab-zieme,45 itab-netwr,50 itab-waerk..
    endloop.
    Initialization.
    at selection-screen.
    IF   s_vbeln is initial and
         s_vkorg is initial and
         s_vtweg is initial and
         s_spart is initial.
        MESSAGE e000(zam).
      ENDIF.
      IF not s_vbeln is initial.
       select vbeln  auart netwr waerk from vbak into table itab where vbeln
                                                                 in s_vbeln.
        IF sy-subrc NE 0.
             MESSAGE e001(zam).
                 ENDIF.
        else.
        if not  s_vkorg is initial.
         select vbeln auart netwr waerk from vbak into table itab
                                         where vkorg = s_vkorg.
             if sy-subrc NE 0.
                 message e002(zam).
                         endif.
                          endif.
        If not s_vtweg is initial.
         select vbeln auart netwr waerk from vbak into table itab
                                          where vtweg = s_vtweg.
           If sy-subrc NE 0.
                message e003(zam).
                      endif.
                       endif.
         if not s_spart is initial.
            select posnr matnr zmeng zieme from vbap into table itab
                                               where spart = s_spart.
            if sy-subrc NE 0.
                 message e004(zam).
                     endif.
                       endif.
       ENDIF.

    The JOIN looks OK.
    You can move the document type to the beginning of the internal table and sort on it when the data is collected.Then:
      LOOP AT itab.
        AT NEW auart.
    * Totals
        ENDAT.
        WRITE :  /5 itab-vbeln,15 itab-posnr,25 itab-auart,
                 30 itab-matnr,35 itab-zmeng,40 itab-zieme,
                 45 itab-netwr,50 itab-waerk..
      ENDLOOP.
    Rob

  • Ideas for making CD from one long audio file

    Hi. Any angels out there willing to suggest the easiest way to make a CD of songs from one long audio file? I'm a teacher and recorded my little 4 year old students singing all their favorite songs. Now I want to turn it into a CD for parents. Should I create new files for every song, cut and paste that part of the audio file into its own song file, save, then throw them all into wave burner? Seems laborious but can't figure another way. Thanks if you've got an idea!

    I've only used WB once, so I THINK this is the way to do it:
    Import the whole single track into WB, and use the scissor tool to cut the file where you want the new track to begin. Wherever you cut WB will make a new track. Then you can tweak the beginning and end of tracks, or do fades accordingly. When you burn it will create a CD with these tracks.

  • Any ideas for making work an 2004 photo printer in Mavericks.

    The generic postscript driver does not have the 4x6'' paper the printer support. (It is a Sony DPP-FP30... and Sony does not have Mac drivers)

    Per the specs, that printer never supported OS X.  You'll want to either run Windows XP to access it — as a guest in a virtual machine or via Boot Camp, or via some other Windows XP system — or using a hack-around via a camera, or you'll end up replacing the printer.
    You'll spend more than US$200 to US$400 to get that printer to work; that's the price of an entry-level replacement dye sublimation printer on Amazon.    Assuming the printer supports some sort of protocol and has some mildly capable on-board rendering — it supposedly prints from cameras, which don't include rendering — then you'd need to find or write the CUPS driver support for the printer.   You'll need to find the specs for the interface, which may not be easy.  That's a somewhat manageable project, but you'll still almost certainly blow through more time and effort and cash than that printer is worth.  If you can't find the specs for the printer interface — a situation which is unfortunately common — reverse-engineering the interface and writing the software will definitely cost more than a replacement printer.
    Based on this and this — the latter page has one potential work-around to continue usage, using a camera as a file transfer device, though with the migration of OS X to Intel, the binary formats might now be little-endian again — this support didn't exist when the printer was new, and I seriously doubt it's been added.

  • An idea for making this community better...

    ...not make it so frustrating to set up an account.
    I would like some help. Not sure if this is the place to go to get help. I plan on sending a PM to an admin, but I'm posting this here as a reference point.
    11/15 - Had a question about my new cell phone and couldn't find the answer in the manual, or anywhere, so I discovered these forums, and thought this would be a great way to get the answer.
    I was already logged in to My Verizon. I clicked over to the forums, did some searching, couldn't find the answer. So I thought I would post my question. I clicked the "create new post" button and was prompted to log in. I enter my "My Verizon" user id and password (wondering if it would work...) and was taken to a page asking for name and email address which I entered. I was then taken to a page that asked for screen name and other details which I entered. I then posted my question...
    http://community.vzw.com/t5/Cell-Phone-General-Devices/Delete-change-Voicemail-entry-in-contact-list...
    11/17 - I came back to the forums (without logging in to anything first) by going directly to the URL above (which I had saved on my desktop). I noticed there was an answer, but I see I need to clarify my question. So I go to log in. I enter the same user id and password I did on 11/15 and was told the combination is invalid. So I went to the "forgot my user id" link, entered the information requested and was told that the account needs to be activiated. So I then (perhaps foolishly) went back to the beginning and clicked on the "register" link. I put in my "My Verizon" user id and password -- AND IT TOOK IT AS NOT BEING A DUPLICATE. But wait, this is the same user id/password I used two days ago, and that I was just told are invalid. Anyway, so I was then taken to a screen asking for a screen name and email address, and you know what comes next...
    I entered "noncitizen" and my email address and was told that both that screen name and email address are already in use.
    Really, by whom? Under what user id?
    I then looked for some kind of a contact link, or help link, or anything, but it seems that unless you have a valid account on the forums you can't get help with the forums. So I setup this account with another "screen name" (angry_user) and a different email address, that I was hesitant to use because it's not one I give out often.
    So basically, this is what I would like to happen. (Of course I can wish in one hand and... well you know the rest.)
    I would like the "noncitizen" screen name to be assocaited with the "noncitizen" user id. I'm befuddled as to why they are not the same. I might be old-school but I've never been to a forum where you have a user id AND a "screen name". Normally the name you use to log in is your "screen name". Now how that is to be accomplished I will leave to the admin who understands how these associations work. But what I would really like (just because I'm terribly curious) is to know what user id is registered and using the screen name "noncitizen" and my other email address. If it's not me, then who is. Maybe my doppleganger posted that question the other day.
    If that means completely removing that account, and this account, and both screen names, and anything I've every posted here (to date, two posts) then please, blow it away!
    Sorry if this sounds angry. It's meant to sound playfully cynical. I am a product of my generation. Perhaps I should have made my "screen name" for this "user id" playfully_cynical. Oh well, guess I'll have to create another account for that.
    I've tried to make this as clear as possible (you only do so much with mud). I did try the main "contact" page on verizon.com and ended up getting someone who (apparently) removed my "My Verizon" account and instructed me to re-enroll. Um,thanks. I say "apparently" because this morning My Verizon still works for me. There *are* strength in numbers, but there are weaknesses as well. The most typical is poor customer service. Oh wait, I'm asking for help, forget I said that...
    Thanks!!!

    You can start this way
    1. Find all active authors
    2. Find the number of papers for each active author
    3. count the number of authors for each department
    4. Find the average number of papers and the number of autors for each department
    5. Find out what is still missing.

  • Lock my iPad asking for PUk code I have no idea what is that

    Need help locked my iPad asking for PUK code to unlock and I have no idea

    I don't think you can, you could try to email apple about the problem or depending on what you mean by "info" if it is just apps you can re download them again once you restore it.

  • Any suggestions for my code.

    Hi,
    I wrote this little piece of code to reduce some of the work I need to do when doing database access. I intend to use if with mySQL and mostly web based applications. It'll probably use it quite a bit, and since it's my first try at writing something like this I figured I'd post the code to see if anyone can find any problems. I've already tested it and it works, so I'm mostly interested in any feedback about performance issues.
    I'd really like to know if there's any way I can get the number of rows in a result set before I start going through it. That way I could return the data in an Object[][] array (I'd assume it'd be a little faster to add values to than the ArrayList).
    Here's the code...
    * SQLGruntBean.java
    * Created on November 22, 2002, 12:37 PM
    package com.vacode.beans.sql;
    import java.sql.*;
    import java.util.*;
    /** This bean is a generic class that can be used to access any type of SQL
    *  database.  To use it with an application that accesses an SQL database
    *  do the following:
    *  <p>1. Create a new instance of SQLGruntBean.</p>
    *  <p>2. Set the SQL connection source by calling setConnection(Connection).</p>
    *  <p>3. Set the SQL query you wish to perform by calling setSqlQuery(String).
    *  <br><b>Note:</b> You may replace all values with question mark place holders
    *  as long as you also perform step 4.</p>
    *  <p>4. (OPTIONAL) Set the values that are represented by question mark place
    *  holders by calling setSqlValues.  This method requires an Object array as
    *  input.</p>
    *  <p>5. (OPTIONAL) Set the maximum number of results to be retrieved by calling
    *  setMaxRows.  If left unset it will default to 100.  This method should not
    *  be used as a replacement for the LIMIT parameter in an SQL query.  It is
    *  merely a backup in case an excessive number of results are returned
    *  erroneously.</p>
    *  <p>6. Once all the necessary variables are set you may call either
    *  executeQuery or executeUpdate to perform the intended task.</p>
    *  <p>     <b><i><u>EXAMPLE</u></i></b></p>
    *  <p>
    *  <code>
    *  <br>SQLGruntBean sgb = new SQLGruntBean();
    *  <br>Object[] values = new Object[1];
    *  <br>ArrayList data = null;
    *  <br><br>
    *  <br>sgb.setConnection(dataSource.getConnection);
    *  <br>sgb.setSqlQuery("SELECT * FROM USERS WHERE firstName = ?");
    *  <br>values[0] = "John";
    *  <br>sgb.setSqlValues(values);
    *  <br>data = sgb.executeQuery();
    *  </code>
    *  </p>
    *  <p>The necessary try / catch blocks and error handling have been left out of
    *  this example, but will need to be implemented for production code.</p>
    * @author  Vacode Web Systems
    * @version 1.0
    public class SQLGruntBean
        // Define global variables
        private Connection dbConnection = null;
        private String sqlQuery = null;
        private int maxRows = 100;  // Default to 100 in case it is not set
        private Object[] sqlValues = null;
        // End global variables
        /** A write only method for defining the connection to an SQL
         *  database
        public void setConnection(Connection sqlConnectionObject)
         this.dbConnection = sqlConnectionObject;
        /** A write only method for defining the SQL query that is to be
         *  executed.*/
        public void setSqlQuery(String sqlQuery)
         this.sqlQuery = sqlQuery;
        /** Defines the maximum number of rows that are to be retrieved from the
         *  result set.  This is more of a back up than anything as the sql query
         *  should contain a limit parameter if the query is going to return an
         *  excessive number of results. */
        public void setMaxRows(int maximumRows)
         this.maxRows = maximumRows;
        /** A write only method for defining the dynamic values that are
         *  to replace the question mark placeholders in the sql query.*/
        public void setSqlValues(Object[] values)
         this.sqlValues = values;
        /** Used to execute an sql query.  The executed query is defined by calling
         *  setSqlQuery prior to this method.  The database connection to be used
         *  is defined by calling setConnection prior to this method. */
        public ArrayList executeQuery() throws SQLException
         // Define the local variables that will be used within this method
         ArrayList data = null;
         // End local variables
         if(this.sqlValues!=null && this.sqlValues.length>0)
             /* A prepared statement needs to be executed because the
              * sqlQuery is going to contain ? placeholders rather than
              * actual values.  It is necessary to replace these place
              * holders with their corresponding values.*/
             data = executePreparedQuery();
         else
             // A regular sql query needs to be executed.
             data = executeRegularQuery();
         return(data);
        /** Used to execute an sql update.  The executed update is defined by calling
         *  setSqlQuery prior to this method.  The database connection to be used
         *  is defined by calling setConnection prior to this method. */
        public int executeUpdate() throws SQLException
         // Define the local variables that will be used in this method
         int rowsAffected = -1;
         // Done local variables
         if(this.sqlValues!=null && this.sqlValues.length>0)
             /* A prepared update needs to be executed because the
              * sqlQuery is going to contain ? placeholders rather than
              * actual values.  It is necessary to replace these place
              * holders with their corresponding values.*/
             rowsAffected = executePreparedUpdate();
         else
             // We just need to execute a regular sql query
             rowsAffected = executeRegularUpdate();
         return(rowsAffected);
        /** If a prepared statement is needed this method will be called by the
         *  executeQuery method.*/
        private ArrayList executePreparedQuery() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         PreparedStatement pstmt = null;
         ArrayList data = null;
         // End local variables
         try
             pstmt = this.dbConnection.prepareStatement(this.sqlQuery);
             setSqlValues(pstmt, this.sqlValues);
             rs = pstmt.executeQuery();
             /* Closing the PreparedStatement is going to cause the
              * ResultSet to be inaccessible.  Therefore it is necessary to
              * move the data that has just been aquired into an alternate
              * data storage object.*/
             data = processResult(rs);
             // Clean up all of the db resources we have opened
             rs.close();
             rs = null;
             pstmt.close();
             pstmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql query there will still be open db resources.  They need
               * to be closed. */
             if(rs!=null)
              try
              { rs.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              rs = null;
             if(pstmt!=null)
              try
              { pstmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              pstmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
             /* Regardless of what happens we need to return an array of Objects.
              * If the returning value is null it should be handled by the
              * calling class. */
         return(data);
        /** If a regular sql statement is required this method will be called
         *  by the executeQuery method. */
        private ArrayList executeRegularQuery() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         Statement stmt = null;
         ArrayList data = null;
         // End local variables
         try
             stmt = this.dbConnection.createStatement();
             rs = stmt.executeQuery(this.sqlQuery);
             /* Closing the Statement is going to cause the ResultSet to be
              * inaccessible.  Therefore it is necessary to move the data
              * that has just been aquired into an alternate data storage
              * object.*/
             data = processResult(rs);
             // Clean up all of the db resources we have opened
             rs.close();
             rs = null;
             stmt.close();
             stmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql query there will still be open db resources.  They need
               * to be closed. */
             if(rs!=null)
              try
              { rs.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              rs = null;
             if(stmt!=null)
              try
              { stmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              stmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
         return(data);
        /** If a prepared update is needed this method will be called by the
         *  executeUpdate method.*/
        private int executePreparedUpdate() throws SQLException
         // Define the local variables that will be used within this method
         PreparedStatement pstmt = null;
         int rowsAffected = -1;
         // End local variables
         try
             pstmt = this.dbConnection.prepareStatement(this.sqlQuery);
             setSqlValues(pstmt, this.sqlValues);
             rowsAffected = pstmt.executeUpdate();
             pstmt.close();
             pstmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql update there will still be open db resources.  They need
               * to be closed. */
             if(pstmt!=null)
              try
              { pstmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              pstmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
             /* Regardless of what happens we need to return an array of Objects.
              * If the returning value is -1 it should be handled by the
              * calling class. */
         return(rowsAffected);
        /** If a regular sql statement is required this method will be called
         *  by the executeQuery method. */
        private int executeRegularUpdate() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         Statement stmt = null;
         int rowsAffected = -1;
         // End local variables
         try
             stmt = this.dbConnection.createStatement();
             rowsAffected = stmt.executeUpdate(this.sqlQuery);
             // Clean up all of the db resources we have opened
             stmt.close();
             stmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql update there will still be open db resources.  They need
               * to be closed. */
             if(stmt!=null)
              try
              { stmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              stmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
         return(rowsAffected);
        /** used to iterate through the sql values and add them to the
         *  prepared statement object. */
        private void setSqlValues(PreparedStatement ps, Object[] values) throws SQLException
         for(int i=0;i<this.sqlValues.length;i++)
             Object o = this.sqlValues;
         /* SQL starts counting at 1 not 0, so this loop needs to be
         * incremented by 1 for the setObject method to interpret it
         * correctly. */
         ps.setObject(i+1, values[i]);
    /** Used to copy a result set into a persistent object so that it can
    * be used even once the connection to the database has been closed. */
    private ArrayList processResult(ResultSet rs) throws SQLException
         ArrayList data = new ArrayList();
         ResultSetMetaData rsmd = rs.getMetaData();
         int colCount = rsmd.getColumnCount();
         while(rs.next())
         Object[] currentRow = new Object[colCount];
         for(int i=0;i<colCount;i++)
              currentRow[i] = rs.getObject(i+1); //SQL starts at 1 not 0
         data.add(currentRow);
         return(data);
    Thanks for the input,
    Ryan

    I think I have an idea of what you mean. I just want to make sure before I write everything though. I could implement your idea by doing the following right?
    I haven't tried any of this, so if there's minor (syntax) errors just ignore them. I'll fix them later.
    1. Create the following Interface.
    package com.vacode.beans.sql;
    public interface GruntBeanProccessingModule
        public Object get(Object[] properties);
    }2. Force the subclasses to implement the above interface
    public class EmployeeProcessor implements GruntBeanProcessingModule
        public Object get(Object[] properties)
         //make sure the input array is the right length (+ other validation, etc.)
         //create a new EmployeeBean
         //set all the EmployeeBean properties based on the input Object[]
         //return the EmployeeBean
    }3. Make the following additions to my SQLGruntBean class
    private requestedClassType = null;
    public void setRequestedClassType(Object o) // o must be an instance of the requested class
        this.requestedClassType = o;
    //if requestedClassType isn't null then create the ArrayList like this
    while(rs.next())
             Object[] currentRow = new Object[colCount];
             for(int i=0;i<colCount;i++)
              currentRow[i] = rs.getObject(i+1); //SQL starts at 1 not 0
             Class requestedClass = Class.forName(requestedClassType.getClass().getName());
             GruntBeanProcessingModule gbpm = requestedClass.newInstance();
             Object convertedData = gbpm.get(currentRow);
             data.add(convertedData);
         }Of course I'll have to handle any possible exceptions (requestedClassType isn't an instance of GruntBeanProcessingModule, etc.). I also notice the forum replaced some of my [] with <> (I've seen it before though, so you probably already know about it).
    Did I get it right or am I out to lunch :-)
    Thank you very much for the feedback,
    Ryan

  • Validation Rule for making Trading Partner mandatory in FB50

    Hi,
    Validation Rule for making Trading Partner mandatory in FB50
    I am trying to make trading field mandatory in FB50. If trading partner is not entered for the line items in FB50, User should get a  error
    I have tried the  follwiong (at the Line Item level) and it does not work:
    1)
    Prerequiste:
    Transaction code = 'FB50'
    Check:
    Trading Partner = ''
    Message:
    2) 
    Prerequiste:
    SYST-TCODE = 'FB50'
    Check:
    Trading Partner = ''
    Message:
    Any ideas?

    The message will only be issued when the result of the check is false.  If you want to issue an error when a trading partner value is not entered, then your check needs to be Trading partner &lt;&gt; ''.  If the user enters a Trading partner value, the check will be true and no message will be issued.  If the user does not enter a Trading partner, the check will be false and the message will be issued.

  • Reccomend a good IDE for Win95

    I desparately need a good IDE for my old Win95 laptop. I've been trying to do a lot of Java development on this pentium II IBM thinkpad 600 and getting nowhere. Right now I have JBuilder4 foundation installed on it and it's horrible. The code insight doesn't always work. The garbage collector brings all development (typing included) to a halt. Maybe someone can show me how to either fine tune JBuilder4 foundation for Win95 development or reccomend a good free IDE that I could use to replace it. I use Eclipse at work and that's the best but it's too fat for Win95. I just tried to install eclipse on my poor laptop and it won't even get past the splash screen. Help!
    Cliff

    Check out my freeware IDE Gel at http://www.gexperts.com . It is natively compiled for Windows so it is light and fast. It includes most common features such as code assistants (code completion, parameter hints, javadoc identifier, etc) for Java and Jsp, smart project management, integrated source control, etc. You can see screenshots at http://www.gexperts.com/features.html
    Gerald

  • I am making code to try to make a game and my problem is that my code......

    I am making code to try to make a game and my problem is that my code
    will not let it change the hit everytime so im getting the first guy to hit 1 then next hits 8 and so on and always repeats.
    Another problem is that I would like it to attack with out me telling it how much times to attack. I am using Object oriented programming.
    Here is the code for my objects:
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class rockCrab {
         //Wounding formula
         double sL = 70;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 50;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         rockCrab() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              double done = rint(fH - fA);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("Rockcrab hit" +done);
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class self {
         //Wounding formula
         double sL = 1;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 1;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         self() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("You hit" +done);
    }Here is the main code that writes what the objects do:
    class fight {
         public static void main(String[] args) {
              self instance1 = new self();
              rockCrab instance2 = new rockCrab();
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
    }when the code is run it says something like this:
    you hit 1
    RockCrabs health is 9
    RockCrab hit 7
    your health is 38
    you hit 1
    RockCrabs health is 8
    RockCrab hit 7
    your health is 31
    you hit 1
    RockCrabs health is 7
    RockCrab hit 7
    your health is 24
    you hit 1
    RockCrabs health is 6
    RockCrab hit 7
    your health is 17
    my point is whatever some one hits it always repeats that
    my expected output would have to be something like
    you hit 1
    RockCrabs health is 9
    RockCrab hit 9
    your health is 37
    you hit 3
    RockCrabs health is 6
    RockCrab hit 4
    your health is 33
    you hit 2
    RockCrabs health is 4
    RockCrab hit 7
    your health is 26
    you hit 3
    RockCrabs health is 1
    RockCrab hit 6
    your health is 20
    Edited by: rade134 on Jun 4, 2009 10:58 AM

    [_Crosspost_|http://forums.sun.com/thread.jspa?threadID=5390217] I'm locking.

  • Ideas for a beginner to program

    I've started mentoring a young student - teaching him LabVIEW. He
    is enjoying it and we have covered the basics. Now I need to come up
    with a project for him to start writing a program(s) on his own. For
    the time being, I would like to keep it to calculations/analysis/display
    kinds of things (no Daq hardware). I was wondering if anyone had ideas
    (or previous experience) of such kinds of programs - something
    relatively easy at this point, but useful/fun enough to keep him interested.
    Thanks,
    Dave
    David Thomson Original Code Consulting
    www.originalcode.com
    National Instruments Alliance Program Member
    Certified LabVIEW Architect
    There are 10 kinds of people: those who understand binary, and those who don't.

    Here is an idea for a nice little project would be:
    (assuming no Daq or GPIB hardware).
    Open a binary file. Parse the file to identify the OP codes and operands. Translate it to "english". Display the translation and write it to another file.
    You can expand to opening a serial port, communicating to a serial device. Interpret the data (especially if there is some sort of waveform to analyze). Plot the data "real-time". Display warnings or conditions if low or high limits are reached, or if a number of samples has been achieved.
    Prompt for user intervention (what to do with the data, ie: save it to file, display it, print it, etc). Allow for user control of the vi (Run / Pause / Stop / Abort).
    The above should provide basic functionality where ther
    e is no instrument to control or a data-acquisition system to monitor.
    Are you looking for real projects? Maybe a bit more challenging?
    Regards,
    -JLV-

  • Any ideas for a (fairly) simple program?

    Does anybody have any ideas for a fairly simple program that I could try to write (I am a fair programmer, but I'm not to creative)?

    You know, Java Game Programming for Dummies is actually a pretty good book (despite the "Dummies" part!) It is written in 1.0, but it has a "ponglet", card games, and several maze games. All the applets I've tried from them actually work (some typos in the book itself, but the CD is ok). Any of these could be "starter" code.
    Yahoo has a whole bunch of Java applet games. You could try to reproduce pieces of the games you see. (These are also interesting in the sense that you can immediately see what works in a game and what doesn't.)
    It is always fun to write little components. Cool buttons (write a nice little non-rectangular button that lights up or something), text boxes that look like digital displays, funny text labels (maybe with a weird font or with letters that jump all over the place when you mouse over them).. These don't take a whole lot of time to write, but write them well and they are very useful for your future games.
    Enjoy!
    :) jen

Maybe you are looking for

  • Save as file format CSV in Excel

    Does anyone know the correct syntax on this one? I have an excel file which should be saved as CSV. This is what I came up with, but it doesn't run. tell application "Microsoft Excel" activate worksheet "worksheet1" set fileSaveName to get save as fi

  • How does Receiver Determination Step in BPM work?

    Hi, I'm still in trouble with the Receiver determination step in the BPM... Normally, when you use the send step, it sends the message in the flow context. Am I right, when I suppose, that when you put the receiver determination step before this send

  • Error "Subscription Expired" when starting MUSE

    I recently installed MUSE CC as part of the ADOBE CREATIVE CLOUD. I have a current membership and are currently working with InDesign CC, Illustrator CC, Photoshop CC and even Dreamweaver CC in the same machine. I used the installer as with any other

  • Can i Have a Tables Link in CRM.....

    Please anyone is having links of tables used in CRM Sales....let me know the link or documentation.... Thanks, Saurin ..

  • Horizontal Menu Bar (using JQuery as opposed to Spry Assets)

    In older versions, used SpryAssets to create a horizontal menu bar, but that is no longer supported.  CC has lots of JQuery inserts, but none for a Horizontal Menu Bar.  What do i do to create one?