Explain me these codes ...

private var mineField:Array=new Array();
public function Main() {
// mine field creation
for (var i:uint=0; i<FIELD_H; i++) {
mineField[i]=new Array();
for (var j:uint=0; j<FIELD_W; j++) {
mineField[i].push(0);
trace("Row "+i+": "+mineField[i]);
trace("The whole mine field: "+mineField);
// end of mine field creation
This is a system of multiple array. I copied it from the book of game design. I would like you to explain :
"Why in the trace ""whole mine field" is 81 zeros?"
Ok, I predict (I understood from the book), that private var mineField array is array of i and j
I also understood that mineField[i] is an array containing only the i from loop ("0,1,2,3,4,5,6,7,8")
... and mineField[i].push(0) changes all i-s in array to 0 ?
Please, explain, it all mixes in my head together

I presume FIELD_H and FIELD_W are being set up as const variables somewhere else and you're just pasting relevant code. So I'll reply with the same.
What I think you're looking for is to get 9 rows with 9 columns, each creating a random amount of mines. The value should be 0 for no mine or 1 for a mine. You'd just need to rewrite the push(0) so it generated a 0 or a 1.
e.g.:
private var mineField:Array = new Array();
public function Main()
          // mine field creation
          for (var i:uint = 0; i < FIELD_H; i++)
                    mineField[i] = new Array();
                    for (var j:uint = 0; j < FIELD_W; j++)
                              mineField[i].push(Math.round(Math.random()*1));
                    trace("Row " + i + ": " + mineField[i]);
          trace("The whole mine field: " + mineField);
          // end of mine field creation
Now a number between 0 and 1 will populate each slot. If you want it to be another value range like 0 - 100 then simply change it to: Math.round(Math.random()*100)

Similar Messages

  • Need help to explain these codes!!! Urgently!!!

    Hi anyone who's here to help...I am doing my Final year project report now...i dunno how to explain these codes in word...can anyone tell me what it means? what are these codes for...? what does each paragraph indicate?
    thanks.
    sorry, maybe i only insert pieces of the codes and its vague...ok, in this source code...what i dun understand is....i have cut and paste the sections of codes which i dun understand as below..
    bcoz this codes are passed down from my seniors who had graduated...and my task is to explain these codes in the form of a report without me having any background on programming...i tried asking some frens...its either they dunno or forgotten...this is my last hope...thanks again...thanks..
    * new added code */
         Thread scroller;     //for looping purpose
         int loopcounter,count;
         // thread is to allow the program to be called every and then.
         public void init()
              /*new added code */
              loopcounter=0;[list]
    **like whats does "thread scroller" means? Looping purpose? what's looping then?
    **also, i've tried on changing the "Loopcounter = 0" to other numbers like 2 and 5...and when i run it on the appletviewer..my image simply runs out of my page...
    [list]
    *And this part...what does it mean?
    /*new added code*/                                      
                public void start() {                    
                if (scroller == null) {               
                scroller = new Thread(this);         
                scroller.start();                          
        } [list]
    for this section here, i really dunno what it says.. "public void start"--start what? scroller again? new Thread(this)?
    [list]
        public void stop() {    
            if (scroller != null) { 
                scroller.stop();   
                scroller = null; 
        } [list]
    I dunno about this section also.. stops wat??
    [list]
        public void run() {                                                           
              try {Thread.currentThread().sleep(100);}                
                catch (InterruptedException e){}
            for (count=0; count <= 400; ) {  
              try {Thread.currentThread().sleep(20);} 
                catch (InterruptedException e){}  
              rm.load();       
        } [list]
    wat is it runing here? try? catch? for? wat does it mean?????
    [list]
        public void destroy(){;}                  
        public void update(Graphics g){paint(g);}
    }[list]
    now this.. wat is it destroying?? updateing wat???
    [list]
    this is my whole program like...
    import java.awt.*;     /*Contains all of the classes for creating user
                   interfaces and for painting graphics and images.*/
    import java.applet.*;     /*Provides the classes necessary to create an applet and the
                   classes an applet uses to communicate with its applet context.*/
    /* Loadable is required for RealMedia so that it know that this code
    can load images and sounds and has the startUp() method
    /* HotSpotListener is required to let HotSpot call hotSpotEvent(HotSpot) when it
    has been clicked
    //runnable is for looping purpose ....to animate the text or images.
    public class LibraryTest extends Applet implements Loadable, HotSpotListener, Runnable
         // RealMedia will load and save images and sounds.
         // It will also give information on the loading process.     
         RealMedia rm;
         // Four buttons that can be clicked on.
         HotSpot hs1,hs2,hs3,hs4;
         // 1 will show image 0 and 1 will show image 1.
         int x =0;
    /* new added code */
         Thread scroller;     //for looping purpose
         int loopcounter,count;
         // thread is to allow the program to be called every and then.
         public void init()
              /*new added code */
              loopcounter=0;
              // We'll place the buttons ourselves.
              setLayout(null);
              setBackground(Color.white);
              // create the RealMedia object
              rm = new RealMedia(this);
              //Start adding all image files you will use
              // image0 called pic_black
              rm.add("pic_black.jpg","image0");
              rm.add("EG3165 Tutorial 1.jpg","image0_1");
              rm.add("Question.jpg","image0_2");
              rm.add("Solution.jpg","image0_3");
              rm.add("Exercise.jpg","image0_4");
              //rm.add("cute.gif","image0_5");
              rm.add("mac-win.gif","image0_6");
              rm.add("walking-floppy.gif","image0_7");
              rm.add("eg3165_t001ver03_00.gif","image1");
              rm.add("eg3165_t001ver03_01.gif","image2");
              rm.add("eg3165_t001ver03_02.gif","image3");
              rm.add("eg3165_t001ver03_03.gif","image4");
              rm.add("eg3165_t001ver03_04.gif","image5");
              rm.add("eg3165_t001ver03_05.gif","image6");
              rm.add("eg3165_t001ver03_06.gif","image7");
              rm.add("eg3165_t001ver03_07.gif","image8");
              rm.add("eg3165_t001ver03_08.gif","image9");
              // Start button with 4 images
              // 1 Default state, mouseOver and mouseClick state.
              rm.add("1st.gif");
              rm.add("1st.gif");
              rm.add("1st.gif");
              // 2 Other button
              rm.add("prev.gif");
              rm.add("prev.gif");
              rm.add("prev.gif");
              // 3
              rm.add("next.gif");
              rm.add("next.gif");
              rm.add("next.gif");
              // 4
              rm.add("last.gif");
              rm.add("last.gif");
              rm.add("last.gif");
              // load the images now
              rm.load();
         public void startUp()
              // button 1
              hs1 = new HotSpot(this);
              hs1.setImage(rm.get("1st.gif"),1);
              hs1.setImage(rm.get("1st.gif"),2);
              hs1.setImage(rm.get("1st.gif"),3);
              hs1.setBounds(200,515,40,38);
              // same for button 2
              hs2 = new HotSpot(this);
              hs2.setImage(rm.get("prev.gif"),1);
              hs2.setImage(rm.get("prev.gif"),2);
              hs2.setImage(rm.get("prev.gif"),3);
              hs2.setBounds(250,515,40,38);
              // same for button 3
              hs3 = new HotSpot(this);
              hs3.setImage(rm.get("next.gif"),1);
              hs3.setImage(rm.get("next.gif"),2);
              hs3.setImage(rm.get("next.gif"),3);
              hs3.setBounds(300,515,40,38);
              // same for button 4
              hs4 = new HotSpot(this);
              hs4.setImage(rm.get("last.gif"),1);
              hs4.setImage(rm.get("last.gif"),2);
              hs4.setImage(rm.get("last.gif"),3);
              hs4.setBounds(350,515,40,38);
              // Place them
              add(hs1);
              add(hs2);
              add(hs3);
              add(hs4);
              // Repaint makes sure they are immediately visible.
              hs1.repaint();
              hs2.repaint();
              hs3.repaint();
              hs4.repaint();
         // Here the images are drawn.
         public void paint(Graphics g)
              g.setColor(Color.white);
              // When it is still loading show a loading message.
              if (!rm.isLoaded())
                   g.drawString("loading file "+rm.getCurrent(),20,20);
                   g.drawString("of "+rm.getTotalFiles(),20,40);
                   g.drawString("Percent: "+rm.getPercent(),20,60);
                   g.fillRect(20,80,rm.getPercent(),20);
              // Otherwise draw image1 or 2
              else
                   if (x == 0)
                        //place images using x-coordinates, y-coordinates.
                        g.drawImage(rm.get("image0"),20,20,this);
                        g.drawImage(rm.get("image0_1"),80+loopcounter,100+loopcounter,this);
                        g.drawImage(rm.get("image0_2"),190+loopcounter,175+loopcounter,this);
                        g.drawImage(rm.get("image0_3"),240+loopcounter,220+loopcounter,this);
                        g.drawImage(rm.get("image0_4"),290+loopcounter,265+loopcounter,this);
                        //g.drawImage(rm.get("image0_5"),150+loopcounter,285+loopcounter,this);
                        g.drawImage(rm.get("image0_6"),400,370,200,100,this);
                        g.drawImage(rm.get("image0_7"),100,300,this);
                        loopcounter+=2;
                        if (loopcounter == 50)
                        loopcounter = 0;
         // if loopcounter+=2, coordinate=x+loopcounter, y+loopcounter.
         /* e.g. round 1, loopcounter=0, coordinate=1,3 */
         /* e.g. round 2, loopcounter=2, coordinate=3,5 */
         /* e.g. round 3, loopcounter=4, coordinate=7,9 */
                   else if (x == 1)
                        g.drawImage(rm.get("image1"),20,20,this);
                   else if (x == 2)
                        g.drawImage(rm.get("image2"),20,20,this);
                   else if (x == 3)
                        g.drawImage(rm.get("image3"),20,20,this);
                   else if (x == 4)
                        g.drawImage(rm.get("image4"),20,20,this);
                   else if (x == 5)
                        g.drawImage(rm.get("image5"),20,20,this);
                   else if (x == 6)
                        g.drawImage(rm.get("image6"),20,20,this);
                   else if (x == 7)
                        g.drawImage(rm.get("image7"),20,20,this);
                   else if (x == 8)
                        g.drawImage(rm.get("image8"),20,20,this);
                   else if (x == 9)
                        g.drawImage(rm.get("image9"),20,20,this);
         // This method is called when a button has been clicked.
         public void hotSpotEvent(HotSpot hs)
              // if it was button 1 show image1.
              if (hs == hs1)
                   x = 1;
              // else show image2
              else if (hs == hs2)
                   {x = x - 1;
                   if ( x <= 1 ) x = 1;
              else if (hs == hs3)
                   {x = x + 1;
                   if ( x >= 9 ) x = 9;
              else
                   x = 9;
              // and repaint to show them.
              repaint();
         // Necessary for RealMedia to load your images
         public Image loadImage(String file)
              return getImage(getCodeBase(),file);
         // Also required but not used this time.
         public AudioClip loadAudio(String file)
              return getAudioClip(getDocumentBase(),file);
    /*new added code*/
         public void start() {
                if (scroller == null) {
                scroller = new Thread(this);
                scroller.start();
        public void stop() {
            if (scroller != null) {
                scroller.stop();
                scroller = null;
        public void run() {
              try {Thread.currentThread().sleep(100);}
                catch (InterruptedException e){}
            for (count=0; count <= 400; ) {
              try {Thread.currentThread().sleep(20);}
                catch (InterruptedException e){}
              rm.load();
        public void destroy(){;}
        public void update(Graphics g){paint(g);}
    }

    Thread scroller;//for looping purpose
    **like whats does "thread scroller" means? Looping purpose? what's looping then?So, you don't know what a variable declaration is, and you don't know what looping is, and you're unable to find out other than by having somebody here tell you (your school has no library, no bookstore, and no access to google--only to the Java forums).
    Either your school is absolutely backwards and useless, or you're a stupid lazy git who deserves to fail the course. Either way, somebody here posting an answer for you is not going to help you.
    The following might.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

  • Do you know what these codes are meaning?

    Oneday, I imported a PDF file from imslp.org(musical sheets library) in 'S note'application of my SAMSUNG Galaxy note 10.1.
    But I couldn't see any contents of the PDF except just white background.
    I tried some PDF files same way and realized this :
    some PDFs are successed but some PDFs are failed.
    I opened each ohter(successed and failed) using notepad(Windows application).
    The failed PDFs are contented these codes.
    %PDF-1.6
    %栒鞠
    85 0 obj <</Linearized 1/L 1255521/O 87/E 122967/N 8/T 1253774/H [ 416 199]>>
    endobj
    xref
    85 6
    0000000016 00000 n
    0000000615 00000 n
    0000000715 00000 n
    0000000921 00000 n
    0000001071 00000 n
    0000000416 00000 n
    trailer
    <</Size 91/Prev 1253763/Root 86 0 R/Info 84 0 R/ID[<946222D04650744EBA57DADE8DDDC8F0><97F52E964F137945BC0D82D325CDBB5B>]>>
    startxref
    0
    %%EOF
    I think it's a kind of optimization but I don't know the tool of it.
    What tool(program) add the codes like that? I want to let SAMSUNG electronic's technical team know this problem.

    Just so you know: so far as I know the only Adobe PDF application for the iPad is called "Adobe Reader". There are other apps, at least one of which is "Pro" something, but they are not from Adobe.
    I'm not saying anything about which is best, just putting the record straight on whether the app you have is actually an Adobe PDF application...

  • Can someone explain me this code?

    Hi... pls explain me this code if possible.
    try {
    wdContext.nodeStateList().bind( (Z_Hress_P0006_State_Input)model.createModelObject(Z_Hress_P0006_State_Input.class));
    wdContext.currentStateListElement().setI_Withemptyline(true);
    wdContext.currentStateListElement().setI_Countrykey(
                        wdContext.currentCountryRecordsElement().getLand());
                   wdContext.currentStateListElement().modelObject().execute();

    Pankak,
    wdDoInit is a method in Web Dynpro controllers that ie executed when controller code is executed first time (initialized) its never run again in the lifespan of that controller (view controller, component controller, custom controller).
    You can get some more introductory material about Web Dynpro here
    https://www.sdn.sap.com/irj/sdn/developerareas/webdynpro?rid=/webcontent/uuid/063bc942-0a01-0010-e7ae-d138e97acb5a [original link is broken]
    Also I would suggest you to buy the Inside Web Dynpro book.
    http://www.sappressbooks.com/product.cfm?account=&product=H983
    This book will help to make your web dynpro concepts solid. I am assuming you know java.
    Regarding the point, i don't have much idea how to give the points, I assume when you close the question you can assign the points.
    Regards,
    Anand

  • HT5463 In my opinion, when the Silence setting is "only when the device is locked", it contradicts the settings you set above, like Manual. Can someone explain how these settings work together?

    Can someone explain how these settings work together? Manual seams to contraduct the SILENCE setting at the bottom of the Do Not Disturb page. It's very confusing.

    You should have seen information in the support document that you linked from. It used to be with the first version of Do Not Disturb that it would only function when the device was locked. That changed with iOS 7, and not it can be active all of the time. With it on Manual, it is on, but if you have the device "awake" that you can still receive calls/texts, etc. Sort of like you have the phone awake, so it isn't a problem for you to receive things. If you set the settings for Always, this means you can be doing things on the phone and not be disturbed by anything else. Does that make sense?

  • Any problem with these codes?

    I have a variable named playerColor, and a button called black. I need to get the button to change the player's color to black(change the frame number to 2). The second frame of the movieclip player is the same as frame 1, but it's the color black instead of red(red is the default color which is frame 1). I can't get any results with these codes.
    Player:
    this.gotoAndStop(_root.playerColor);
    Button:
    on (release) {
    _root.playerColor = 2;
    File: [url]http://www.mediafire.com/?p8wpnp8p86n58fm[/url]

    Let's say I change the player's color to black. I go to a different frame of the game, then I return, I need it to stay black.
    Note: The player is just a circle.
    I tried to follow this video but I couldn't get anything out of it.
    http://www.youtube.com/watch?v=WcujM0rFUwA

  • How to reduce these code using oop in AS3

    i have 8 movie clip and i use it as a navigation buttons and when clicked it should go to different links. i use these codes but i think these codes are not pure oop so can any one help me to reduce programming using oop but works in same way as it is doing right now.
    the codes are follows
    function buttonmode(link:MovieClip):void{
    link.buttonMode = true;
    buttonmode(rec1_mc);
    buttonmode(rec2_mc);
    buttonmode(rec3_mc);
    buttonmode(rec4_mc);
    buttonmode(rec5_mc);
    buttonmode(rec6_mc);
    buttonmode(rec7_mc);
    buttonmode(rec8_mc);
    function navigate1(e:MouseEvent):void{
    navigateToURL(new URLRequest("http://www.ebpearls.com" ),"_self");
    function navigate2(e:MouseEvent):void{
    trace("Button 2 is Clicked");
    function navigate3(e:MouseEvent):void{
    trace("Button 3 is Clicked");
    function navigate4(e:MouseEvent):void{
    trace("Button 4 is Clicked");
    function navigate5(e:MouseEvent):void{
    trace("Button 5 is Clicked");
    function navigate6(e:MouseEvent):void{
    trace("Button 6 is Clicked");
    function navigate7(e:MouseEvent):void{
    trace("Button 7 is Clicked");
    function navigate8(e:MouseEvent):void{
    trace("Button 8 is Clicked");
    rec1_mc.addEventListener(MouseEvent.CLICK,navigate1);
    rec2_mc.addEventListener(MouseEvent.CLICK,navigate2);
    rec3_mc.addEventListener(MouseEvent.CLICK,navigate3);
    rec4_mc.addEventListener(MouseEvent.CLICK,navigate4);
    rec5_mc.addEventListener(MouseEvent.CLICK,navigate5);
    rec6_mc.addEventListener(MouseEvent.CLICK,navigate6);
    rec7_mc.addEventListener(MouseEvent.CLICK,navigate7);
    rec8_mc.addEventListener(MouseEvent.CLICK,navigate8);

    I think the more OO way is like this:
    1. Create AbstractButton class and save it in a file called AbstractButton.as in the same folder the FLA file resides:
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        public class AbstractButton extends MovieClip
            public function AbstractButton()
                super();
                this.stop();
                this.buttonMode = true;
                this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
                this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
                this.addEventListener(MouseEvent.CLICK, onClick);
            protected function onRollOver(e:MouseEvent):void
                // rollOver behaviour, e.g. this.gotoAndStop(2);
            protected function onRollOut(e:MouseEvent):void
                 // rollOut behaviour, e.g.  this.gotoAndStop(1);
            protected function onClick(e:MouseEvent = null):void
                var data:Object = new Object();
                data.id = this.name;
                var evt:NavEvent = new NavEvent(data, NavEvent.NAV_EVENT, true, true);
                dispatchEvent(evt);           
    2. Link button symbol in your library to the AbstractButton class: right click on it (in library), click Properties, in Linkage section mark Export for ActionScript box and put AbstractButton as Class, Base class field leave empty. If you use more than one button symbols form your library, do the same thing with them.
    3. Create NavEvent class, save it in NavEvent.as file in the same  folder:
    package
         import flash.events.Event;
        public class NavEvent extends Event
             public static const NAV_EVENT:String = "NavEvent";
             public var data:Object;
             public function NavEvent(data:Object, type:String,  bubbles:Boolean, cancelable:Boolean)
                 this.data = data;
                 super(NAV_EVENT, true, true);
    4. Drag your buttons on the stage, give them instance names as you did.
    5. On your main timeline (or in document class if you're using it) use the following code to controll button clicks. Here e.data.id carries the instance name of clicked button.
    this.root.addEventListener(NavEvent.NAV_EVENT, handleNavEvent);
    function handleNavEvent(e:NavEvent):void
        switch (e.data.id)
            case "rec1_mc":          
                navigateToURL(new URLRequest("http://www.ebpearls.com" ),"_self");
                break;
            case "rec2_mc":
                trace("2 clicked");
                break;
            case "rec3_mc":
                trace("3 clicked");
                break;
              // and so on       

  • Please help 'Translate' These codes from AS2 to AS3 for me

    Hi, i need help 'translating' these codes from Action Script 2 to Action Script 3. Please Do it for me:
    toc    loadText = new LoadVars();
        loadText.load("Curie.txt");
        loadText.onLoad = function(success) {
            if (success) {
                // trace(success);
                Curie.html = true;
                Curie.htmlText = this.Curie;
    Please translate it for me, i need it ASAP thanks
    Kenneth

    Thank you for helping me
    Kenneth
    Date: Thu, 15 Oct 2009 05:49:14 -0600
    From: [email protected]
    To: [email protected]
    Subject: Please help 'Translate' These codes from AS2 to AS3 for me
    Take a look at that:
    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/migration.html
    There is a LoadVars section on that.
    There is also a tutorial here:
    http://www.republicofcode.com/tutorials/flash/as3externaltext/
    Cheers,
    CaioToOn!
    >

  • Stumped in a space invader tutorial: why are these code for?

    EDIT: Hi thanks to those who viewed my post and attempted to help. I found the answer, it's called double buffering.
    Anyway if you guys want to make additional infos or add something feel free to do so. Because I don't fully understand what's going on. (like what kind of graphic does getGraphics() return?)
    Thanks again!
    Hi, I'm following a tutorial about creating a space invaders game and it doesn't really explain much the objects and methods.
    Here's what I've done so far:
    import java.awt.Canvas;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    import java.util.HashMap;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Invaders extends Canvas{
         static final int WIDTH = 800;
         static final int HEIGHT = 600;
         static final int SPEED = 10;
         HashMap sprites;
         int posX, posY, vX;
         BufferedImage buffer;
         Invaders(){
              sprites = new HashMap();
              posX = WIDTH/2;
              posY = HEIGHT/2;
              vX = 2;
              buffer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
              JFrame ventana = new JFrame("Space Invaders");
              JPanel panel = (JPanel)ventana.getContentPane();
              setBounds(0, 0, WIDTH, HEIGHT);
              panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
              panel.setLayout(null);
              panel.add(this);
              ventana.setBounds(0, 0, WIDTH, HEIGHT);
              ventana.setVisible(true);
              ventana.addWindowListener(new WindowAdapter(){@Override
              public void windowClosing(WindowEvent e) {
                   // TODO Auto-generated method stub
                   super.windowClosing(e);
              ventana.setResizable(false);
              ventana.setIgnoreRepaint(true);
         public BufferedImage loadImage(String name) {
              URL url = null;
              try {
                   url = getClass().getClassLoader().getResource(name);
                   return ImageIO.read(url);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return null;
         BufferedImage getSprite(String name){
              BufferedImage img = (BufferedImage)sprites.get(name);
              if (img == null){
                   img = loadImage("res/"+name);
                   sprites.put(name, img);
              return img;
         public void paintWorld(){
              Graphics g = buffer.getGraphics();
              g.setColor(getBackground());
              g.fillRect(0, 0, getWidth(), getHeight());
              g.drawImage(getSprite("bicho.gif"), posX, posY, this);
              getGraphics().drawImage(buffer, 0, 0, this);
         public void paint(Graphics g){}
         public void update(Graphics g) {}
         public void updateWorld() {
              posX += vX;
              if (posX < 0 || posX > WIDTH) vX = -vX;
         public void game(){
              while (isVisible()){
                   updateWorld();
                   paintWorld();
                   paint(getGraphics());
                   try {
                        Thread.sleep(SPEED);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Invaders inv = new Invaders();
              inv.game();
    }I tried reading the Java API but I don't get what it's saying for these:
    buffer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //what is the meaning of TYPE_INT_RGB?
    ventana.setIgnoreRepaint(true); //why ignore repaint?
    public void paintWorld() {
    Graphics g = buffer.getGraphics();
    g.setColor(getBackground());
    g.fillRect(0,0,getWidth(),getHeight());
    g.drawImage(getSprite("bicho.gif"), posX, posY,this);
    getGraphics().drawImage(buffer,0,0,this); //why add this line?
    }and lastly:
          public void game() {
            while (isVisible()) {
             updateWorld();
             paintWorld();
             paint(getGraphics()); //why call paint here?
             try {
                Thread.sleep(SPEED);
             } catch (InterruptedException e) {}
         }I understand the rest of the code, it's just the parts that I've mentoined that I can't really understand.
    I'd appreciate any help. Thanks! :)
    Edited by: ajushi on Dec 16, 2007 2:38 PM
    Edited by: ajushi on Dec 16, 2007 2:43 PM
    Edited by: ajushi on Dec 16, 2007 2:52 PM

    I got the sucker to draw but now it won't stop! You have to kill it's JVM with taskManager... and I haven't got a clue how to fix it.
    package forums;
    import java.util.Map;
    import java.util.HashMap;
    import java.awt.Canvas;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Container;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.io.IOException;
    public class SpaceInvaders extends JFrame
      private static final long serialVersionUID = 0L;
      private static final int WIDTH = 800;
      private static final int HEIGHT = 600;
      private static final int SPEED = 100;
      private int posX = WIDTH/2;
      private int posY = HEIGHT/2;
      private int vX = 5;
      private BufferedImage buffer = null;
      private Container pane = null;
      private BufferedImage image = null;
      SpaceInvaders() {
        super("Space SpaceInvaders");
        super.setBounds(0, 0, WIDTH, HEIGHT);
        super.setResizable(false);
        super.setIgnoreRepaint(true);
        super.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        super.setLayout(null);
        this.addWindowListener(
          new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
              super.windowClosing(e);
        pane = super.getContentPane();
        pane.setPreferredSize(new Dimension(WIDTH,HEIGHT));
        pane.setLayout(null);
        try {
          image = ImageIO.read(new URL("file:///c:/java/home/src/krc/games/bomb.jpg"));
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException("failed to load image: "+e.toString());
        buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        super.setVisible(true);
      public void paintWorld() {
        Graphics g = buffer.getGraphics();
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());
        g.drawImage(image, posX, posY, this);
        this.getGraphics().drawImage(buffer, 0, 0, this);
      public void paint(Graphics g){}
      public void update(Graphics g){}
      public void updateWorld() {
        posX += vX;
        if (posX < 0 || posX > WIDTH) {
          vX = -vX;
      public void play() {
        while (super.isVisible()){
          updateWorld();
          paintWorld();
          Thread.currentThread().yield();
          try{Thread.sleep(SPEED);}catch(InterruptedException eaten){}
      public static void main(String args[]) {
        try {
          java.awt.EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                SpaceInvaders game = new SpaceInvaders();
                game.play();
        } catch (Exception e) {
          e.printStackTrace();
    }

  • What can be done to make these code examples work on web Browsers?

    I have tried numerous versions of ?Hello World? examples over the web to display the text on a web page. All the examples work on my local machine in the application viewer, but they don?t work when from a web browser. I have tried both Firefox and IE.
    Some of them include:
    [http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java|http://java.sun.com/docs/books/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java]
    Firefox error:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassCastException: start.HelloWorldSwing cannot be cast to java.applet.Applet
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception: java.lang.reflect.InvocationTargetException [http://en.wikipedia.org/wiki/Swing_%28Java%29|http://en.wikipedia.org/wiki/Swing_%28Java%29]
    Error when viewed on Firefox:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassCastException: start.SwingExample cannot be cast to java.applet.Applet
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Exception: java.lang.reflect.InvocationTargetException An Ideal Code if someone could decipher why it fails from a browser is:
    import javax.swing.*;
    public class SwingHelloWorld extends JFrame {
        public SwingHelloWorld(String name) {
          super(name);
          this.setDefaultCloseOperation(EXIT_ON_CLOSE);
          JLabel label = new JLabel(name);
          // label.setPreferredSize(new Dimension(210, 80));
          this.getContentPane().add(label);
          this.pack();
          this.setVisible(true);
      public static void main(String argv[]) {
            SwingHelloWorld swingHelloWorld = new SwingHelloWorld("This would be great if it worked via a browser!");
    } Error from Firefox:
    java.lang.reflect.InvocationTargetException
         at com.sun.deploy.util.DeployAWTUtil.invokeAndWait(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.runOnEDT(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: java.lang.InstantiationException: start.SwingHelloWorld
         at sun.plugin2.applet.Plugin2Manager$12.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.InstantiationException: start.SwingHelloWorld
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         ... 9 more
    Exception: java.lang.reflect.InvocationTargetException The latter code is very short and would serve the intended purpose most ideal. It can accept input and allow me to replace the ?System.out.println? function that works so well to display when working with code in the development environment.
    Thanks in advance for any input on this.
    -- L. James
    L. D. James
    Edited by: apollothethird on Mar 8, 2010 5:05 AM

    paulcw wrote:
    As per your suggestion, I changed the &#147;extend&#148; to Applet and changed it to &#147;JApplet&#148;. Making that change will result in code that won?t even compile.Right. You're going to have to change your program to actually work as an applet.
    Either that or use Java Web Start, which is probably the best option.Thanks. The code I presented was my attempt to find examples that represented the advice I thought I was getting (to use JFrame and JLabels). I?m changing the direction of the examples I?m looking for now.
    >
    The current code as published by sun.com actually compiles and displays in the Netbeans programming environment. It looks great. But I?m kind of stuck with the missing link for making it output to the browser.Different things work in different ways. You wrote a standalone application which compiles and runs. Writing an applet is a different thing, and works in a different way. Read the applet tutorials for more information on applet methods and the applet lifecycle.Thanks. I?m reading. I try to execute some of the examples from my reading, but and stuck. So, I?m asking for some clarifications of some of the components I?m stuck with. Having some of my questions answered would help me to understand better the lots of reading and studying that I?m doing.
    I?m taking in all the advice that is given, and I appreciate it a lot.
    >
    Thanks for the hints. Thanks also in advance if you happen to know how to change the extend to Applet or JApplet instead of &#147;JFrame&#148; and it works.This is made clear in the applet tutorials. It's more than just changing the class to extend. Note that Applet/JApplet extends Panel/JPanel, so that changes the way your program is constructed. Basically, you don't have to create your own frame.Also, I don?t want a frame. I?m trying to find a way to make my question clear. I appreciate the time you?re taking to respond to a new user?s scope.
    >
    But again, web start is probably a better choice if you have a running app.
    You should probably abandon the idea that you just have to nudge a program slightly in a new direction to make a wholly new thing. Programming is all about reducing complex problems to a set of concrete solutions.Absolutely. I have some examples that will actually print a string to a browser. However, those examples will print what?s written in the immediate code, with no apparent method (that I can) make into a variable. The ?Hello World? example that I find that has a main class is the ones that are failing. The ones that don?t have a main class will print.
    I have been trying to find a way to pass a variable to this code that will print over the web:
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    import javax.swing.JLabel;
    public class HelloWorld extends JApplet {
        //Called when this applet is loaded into the browser.
        public void init() {
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        JLabel lbl = new JLabel("Hello World");
                        add(lbl);
            } catch (Exception e) {
                System.err.println("createGUI didn't complete successfully");
    }However when I try to add a functioning main class and change the ?Hello World? to a string variable, it fails. I understand it fails because I?m having a missing link about how to turn the class into something that can take input.
    I know I?ll be ridiculed for the example I?m about to print, but I?m printing it to give an example of having a variable for my output.
    Look at the code that fails (just to get an idea of what I?m trying to explain):
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package test1;
    * @author teama
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    import javax.swing.JLabel;
    public class HelloWorld extends JApplet {
        //Called when this applet is loaded into the browser.
        public void init() {
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run(String myhello) {
                        JLabel lbl = new JLabel(myhello);
                        add(lbl);
            } catch (Exception e) {
                System.err.println("createGUI didn't complete successfully");
            public static void main(String[] args) {
                // This is the output of my calculation
                // HelloWorld.void("Hello World")
                run("My Hello")               
    } -- L. James
    L. D. James

  • What is "verzoekcode" ? Where can I find these code ?

    We can not find the request code. Where can I find these request code ?

    https://exception.licenses.adobe.com/aoes/aoes/v1/cst1?locale=en
    Hilfe
    http://helpx.adobe.com/x-productkb/global/service1.html

  • Explaination of simple code?!?!?

    hi, im new to java & to this forum.
    im a java noob!!!
    I was wonder if someone could explain to me
    how this code prints out 120 for "r"?
    (step by step)
    thx java genius's
    int [] x;
    int r;
    int i;
    /* 1 */ x = new int[] {2, 3, 4, 5, 6};
    /* 2 */ r = 1;
    /* 3 */ i = x.length-1;
    /* 4 */ while ( i > 0 )
    /* 5 */ r = r * x;
    /* 6 */ if (r > 100)
    /* 7 */ i = i - 1;
    else
    /* 8 */; // do nothing
    /* 9 */ i = i - 1;
    /* 10 */ System.out.println( r );                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    120 = 4 * 5 * 6
    when > 100 it skip a value and ignores the first value so it stops.

  • For the last time. What's wrong in these code ? please let your opnion.

    I can'nt get the data from the list in <c:forEach> tag, are you able to see the possible error?though the jsp page is returned, it is all in blank.
    the codes are these:
    -my conecction and where i get my list
    package teste;
    public class Data {
        Connection con;
        Detalhes detalhes;
        int codigo;
        ArrayList  list;
        public Data()throws Exception {       
            try {
                Class.forName("org.gjt.mm.mysql.Driver");
                con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/Loja?user=root&password=131283");            
            } catch (Exception ex) {
                throw new Exception(" Database not found!!" +
                    ex.getMessage());
        public void remove() {
            try {
                con.close();
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
        public void setCodigo(int codigo){
            this.codigo = codigo;
        public Detalhes getDetalhes(){
            try {
                String selectStatement = "select * from produto where codigo="+codigo;
                PreparedStatement prepStmt = con.prepareStatement(selectStatement);
                ResultSet rs = prepStmt.executeQuery();
                while(rs.next())
                     detalhes = new Detalhes(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getInt(4));          
                prepStmt.close();
            }catch(Exception e){
           return detalhes;
        public ArrayList getList(){
            try {
                list = new ArrayList();
                String selectStatement = "select * from produto";
                PreparedStatement prepStmt = con.prepareStatement(selectStatement);
                ResultSet rs = prepStmt.executeQuery();
                while(rs.next()){
                     detalhes = new Detalhes(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getInt(4));          
                     list.add(detalhes);
                prepStmt.close();
                Collections.sort(list);
            }catch(Exception e){
                System.out.println(e.getMessage());
            return list;
    }    - the object where i store and show the data through the methods
    package teste;
    public class Detalhes {
        private String titulo;
        private String autor;
        private Double preco;
        private int codigo;
        public Detalhes(String titulo, String autor, Double preco, int codigo) {
            this.titulo = titulo;
            this.autor = autor;
            this.preco = preco;
            this.codigo = codigo;       
        public String getTitulo(){
            return titulo;
        public String getAutor(){
            return autor;
        public Double getPreco(){
            return preco;
        public int getCodigo(){
            return codigo;
    }-my inicial context class
    package teste;
    import javax.servlet.*;
    public final class ContextPage implements ServletContextListener {
        private ServletContext context = null;
        NewClass bookDB;
        public void contextInitialized(ServletContextEvent event) {
            context = event.getServletContext();
            try {
                bookDB = new NewClass();
                context.setAttribute("bookDB", bookDB);
            } catch (Exception ex) {
                System.out.println("Couldn't create bookstore database bean: " +
                    ex.getMessage());
        public void contextDestroyed(ServletContextEvent event) {
            context = event.getServletContext();
            NewClass dados = (NewClass) context.getAttribute("bookDB");
            if (dados != null) {
                dados.remove();
            context.removeAttribute("bookDB");              
    }- my jsp page
    <p><b><h1>Resultado:</h1></b></p><br>
    <jsp:useBean id="dataSource" class="teste.Data" scope="page" >
           <jsp:setProperty name="dataSource" property="codigo" value="${param.theCode}"/>          
    </jsp:useBean>
    <c:forEach var="book" items="${dataSource.list}">
        <p><b><h1><font color="red">${book.titulo}<h1></b></p>        
        <p><b><h1><font color="red">${book.autor}<h1></b></p>        
        <p><b><h1><font color="red">${book.preco}<h1></b></p>        
        <p><b><h1><font color="red">${book.codigo}<h1></b></p>        
    </c:forEach>
    <c:out value=${bookList}/>

    First of all: Don't try to force a response by using a subject "For the last time ..."
    Independent of your original problem
    There are a lot of things which are not correct in your code.
    // i would never use the user root to access a database :-(
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/Loja?user=root&password=131283");
    public Detalhes getDetalhes(){
            PreparedStatement prepStmt = null;
            ResultSet rs = null;
            try {
                // use place holders when working with prepared statements
                //  String selectStatement = "select * from produto where codigo="+codigo;
                 String selectStatement = "select * from produto where codigo= ?" ;
                PreparedStatement prepStmt = con.prepareStatement(selectStatement);
                prepStmt.setInt(1,codio);
                rs = prepStmt.executeQuery();
                while(rs.next())
                     // use colomn names rather than indices
                     detalhes = new Detalhes(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getInt(4));
                rs.close();
                rs = null;
                prepStmt.close();
                prepStmt = null;
            // don't catch Exception
            }catch(SQLException sqle){
                // try and forget - is allways very useful
                Logger.getLogger(this.class.getName()).log(Level.SERVE, sqle.getMessage(), sqle);
            } finally {
               // close prepared statements and result sets within finally blocks
               if (rs != null) {
                  try {
                     rs.close();
                  } catch (SqlException sqle) {
                     Logger.getLogger(this.class.getName()).log(Level.FINEST , sqle.getMessage(), sqle) ;
               if (prepStmt != null) {
                  try {
                       prepStmt.close();
                  } catch (SQLException sqle) {
                      Logger.getLogger(this.class.getName()).log(Level.FINEST , sqle.getMessage(), sqle) ;
           return detalhes;
    public final class ContextPage implements ServletContextListener {
        // don't use a member field here the context is passed within the event.
        private ServletContext context = null;
        // makes no sense to save it as member field.
        // what's NewClass ?
        NewClass bookDB;
        public void contextInitialized(ServletContextEvent event) {
            context = event.getServletContext();
            try {
                bookDB = new NewClass();
                context.setAttribute("bookDB", bookDB);
            } catch (Exception ex) {
                System.out.println("Couldn't create bookstore database bean: " +
                    ex.getMessage());
        public void contextDestroyed(ServletContextEvent event) {
            context = event.getServletContext();
            NewClass dados = (NewClass) context.getAttribute("bookDB");
            if (dados != null) {
                dados.remove();
            context.removeAttribute("bookDB");              
    <%-- I don't see where a bean with id dataSource and scope page is set
             if the bean does not exist a new bean will be created
             nobody ever calls the remove method of your Data bean
             what's param.theCode ?
    --%>
    <jsp:useBean id="dataSource" class="teste.Data" scope="page" >
           <jsp:setProperty name="dataSource" property="codigo"
    value="${param.theCode}"/>          
    </jsp:useBean>
    }So now you've got a lot of work.
    If you have fixed all the problems I've told you and you have still problems you can come
    back and ask additional questions.
    andi

  • Can anyone explain why the code compiles on one database but not another?

    I have two databases, both running 10.2.0.4, same hardware/OS platform.
    On one database, this code compiles just fine, on the second database, I get errors as shown below:
    SQL> SET SERVEROUTPUT ON SIZE 1000000;
    SQL>
    SQL> create or replace procedure testproc as
    2 vCount number;
    3 vCmd varchar2(2048);
    4 vLastName varchar2(30);
    5 vFirstName varchar2(30);
    6 vPK integer := 0;
    7 vSortLN varchar2(30);
    8 vSortFN varchar2(30);
    9 cursor cPERSON is
    10 select LastName,
    11 FirstName
    12 from GENERIC.PERSON
    13 order by LastName, FirstName;
    14 BEGIN
    15 select count(*) into vCount from USER_OBJECTS where object_name = 'ML4TEMPPERSON';
    16
    17 IF (vCount = 0) THEN
    18 /* NOTE: Omit semi-colon from command. */
    19 vCmd := 'create table ML4TEMPPERSON (PK integer not null, LastName varchar2(30), SortLN varchar2(30), FirstName varchar2(30), SortFN varchar2(30))';
    20 Execute Immediate vCmd;
    21 vCmd := 'alter table ML4TEMPPERSON add (constraint XPKML4TEMPPERSON PRIMARY KEY (PK))';
    22 Execute Immediate vCmd;
    23 END IF;
    24
    25 delete from ML4TEMPPERSON;
    26
    27 for P in cPERSON
    28 loop
    29 vLastName := rpad(P.LastName, 30, ' ');
    30 vFirstName := rpad(P.FirstName, 30, ' ');
    31 vSortLN := vLastName;
    32 vSortFN := vFirstName;
    33 DBMS_OUTPUT.PUT_LINE(vLastName || ', ' || vFirstName);
    34 vPK := vPK+1;
    35 INSERT into ML4TEMPPERSON
    36 ( PK, LastName, SortLN, FirstName, SortFN)
    37 values
    38 (vPK, vLastName, vSortLN, vFirstName, vSortFN);
    39 end loop;
    40 IF (vPK > 0) THEN
    41 COMMIT;
    42 END IF;
    43 END;
    44 /
    Warning: Procedure created with compilation errors.
    SQL> show errors
    Errors for PROCEDURE TESTPROC:
    LINE/COL ERROR
    25/3 PL/SQL: SQL Statement ignored
    25/15 PL/SQL: ORA-00942: table or view does not exist
    35/7 PL/SQL: SQL Statement ignored
    35/19 PL/SQL: ORA-00942: table or view does not exist
    SQL>

    Your table ML4TEMPPERSON doesn't exist in your second database, and you want do delete ans insert, may be in first database the table ML4TEMPPERSON exist
    Try this code. /* Formatted on 2009/05/21 09:10 (Formatter Plus v4.8.8) */
    SET SERVEROUTPUT ON SIZE 1000000;
    CREATE OR REPLACE PROCEDURE testproc
    AS
       vcount       NUMBER;
       vcmd         VARCHAR2 (2048);
       vlastname    VARCHAR2 (30);
       vfirstname   VARCHAR2 (30);
       vpk          INTEGER         := 0;
       vsortln      VARCHAR2 (30);
       vsortfn      VARCHAR2 (30);
       CURSOR cperson
       IS
          SELECT   lastname, firstname
              FROM generic.person
          ORDER BY lastname, firstname;
    BEGIN
       SELECT COUNT (*)
         INTO vcount
         FROM user_objects
        WHERE object_name = 'ML4TEMPPERSON';
       IF (vcount = 0)
       THEN
    /* NOTE: Omit semi-colon from command. */
          vcmd :=
             'create table ML4TEMPPERSON (PK integer not null, LastName varchar2(30), SortLN varchar2(30), FirstName varchar2(30), SortFN varchar2(30))';
          EXECUTE IMMEDIATE vcmd;
          vcmd :=
             'alter table ML4TEMPPERSON add (constraint XPKML4TEMPPERSON PRIMARY KEY (PK))';
          EXECUTE IMMEDIATE vcmd;
       END IF;
       vcmd := 'delete from ML4TEMPPERSON';
       EXECUTE IMMEDIATE vcmd;
       FOR p IN cperson
       LOOP
          vlastname := RPAD (p.lastname, 30, ' ');
          vfirstname := RPAD (p.firstname, 30, ' ');
          vsortln := vlastname;
          vsortfn := vfirstname;
          DBMS_OUTPUT.put_line (vlastname || ', ' || vfirstname);
          vpk := vpk + 1;
          vcmd :=
                'INSERT into ML4TEMPPERSON
    ( PK, LastName, SortLN, FirstName, SortFN)
    values
             || vpk
             || ', '
             || vlastname
             || ','
             || vsortln
             || ','
             || vfirstname
             || ','
             || vsortfn
             || ')';
          EXECUTE IMMEDIATE vcmd;
       END LOOP;
       IF (vpk > 0)
       THEN
          COMMIT;
       END IF;
    END;
    /Edited by: Salim Chelabi on 2009-05-21 06:12

  • Can anyone explain what this code does.

    <b>Below is the FM for a  SAP Exit Variable ( 0FPER - Fiscal Period Variable ) , I would really appreciate if someone can give some explanation what does the code do.</b>
    FUNCTION RSVAREXIT_0F_FPER.
    ""Lokale Schnittstelle:
    *"       IMPORTING
    *"             VALUE(I_VNAM) LIKE  RSZGLOBV-VNAM
    *"             VALUE(I_VARTYP) LIKE  RSZGLOBV-VARTYP
    *"             VALUE(I_IOBJNM) LIKE  RSZGLOBV-IOBJNM
    *"             VALUE(I_S_COB_PRO) TYPE  RSD_S_COB_PRO
    *"             VALUE(I_S_RKB1D) TYPE  RSR_S_RKB1D
    *"             VALUE(I_S_RKB1F) TYPE  RRO01_S_RKB1F
    *"             VALUE(I_THX_VAR) TYPE  RRO01_THX_VAR
    *"       EXPORTING
    *"             VALUE(E_T_RANGE) TYPE  RSR_T_RANGESID
    *"       EXCEPTIONS
    *"              UNKNOWN_VARIABLE
    *"              UNEXPECTED_VARTYPE
    *"              INVALID_PERIV
    *"              VARIABLE_INITIAL
    *"              NO_REPLACEMENT
      data:
      l_s_range   type rs_s_range,
      ld_periv    type rro01_s_rkb1f-periv,
      ld_curdate  like sy-datum,
      ld_poper    like t009b-poper,
      ld_fiscyear like t009b-bdatj.
      refresh e_t_range.
      clear l_s_range.
      l_s_range-sign = 'I'.
      l_s_range-opt  = 'BT'.
      case i_vartyp.
        when rro04_c_vartyp-formula.
    *--- Determine fiscal year variant
          call function 'BWCO_FISCVARNT_GET'
               exporting
                    i_s_rkb1d        = i_s_rkb1d
                    i_s_rkb1f        = i_s_rkb1f
                    i_thx_var        = i_thx_var
               importing
                    e_periv          = ld_periv
               exceptions
                    no_replacement   = 1
                    unknown_variable = 2
                    others           = 3.
          case sy-subrc.
            when 0.
            when 2.
              raise unknown_variable.
            when others.
              raise no_replacement.
          endcase.
          if ld_periv is initial.
            raise invalid_periv.
          endif.
    *--- Determine current fiscal year
          ld_curdate = sy-datum.
          call function 'DATE_TO_PERIOD_CONVERT'
               exporting
                    i_date         = ld_curdate
                    i_periv        = ld_periv
               importing
                    e_buper        = ld_poper
                    e_gjahr        = ld_fiscyear
               exceptions
                    input_false    = 1
                    t009_notfound  = 2
                    t009b_notfound = 3
                    others         = 4.
          if not sy-subrc is initial.
            raise invalid_periv.
          endif.
    *--- Determine the highest fiscal period in the current fiscal year
          CALL FUNCTION 'GET_ACCOUNT_OF_PERIODS'
               EXPORTING
                    I_GJAHR         = ld_fiscyear
                    I_PERIV         = ld_periv
               IMPORTING
                    E_ANZBUPER      = ld_poper
               EXCEPTIONS
                    INPUT_FALSE     = 1
                    T009B_NOTFOUND  = 2
                    T009_NOTFOUND   = 3
                    OTHERS          = 4
          IF SY-SUBRC <> 0.
                raise invalid_periv.
          ENDIF.
    *--- fill value ranges
          l_s_range-low = ld_poper.
          append l_s_range to e_t_range.
        when others.
          raise unexpected_vartype.
      endcase.
    endfunction.

    1) Fiscal year variant is determined using Function Module - 'BWCO_FISCVARNT_GET'
    2) With Fiscal variant & Current Date as input to Function Module - 'DATE_TO_PERIOD_CONVERT' gets Fiscal Year.
    3) With Fiscal year & variant as input to 'GET_ACCOUNT_OF_PERIODS' gets 
    the highest fiscal period in the current fiscal year

Maybe you are looking for