String invaders!

Hi!
My awful version of space invaders is almost ready. I only have problems programming the method where I check whether a rocket hits an alien. This method is called 'controleerHit' in Spel.
Thanks for your help!
import java.applet.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.Object;
import java.util.ArrayList;
import java.util.Random;
//een simpel schietspel van 15 seconden waarbij het ruimteschip dmv raketten bewegende aliens
//moet zien te raken en dmv bewegen zijn positie kan bepalen
public class Spel extends Applet
     //Timers
     Timer nieuwePositieTimer;
     Timer nieuweAlienTimer;
     Timer stopSpelTimer;
     //een nieuwe arraylist bewegendedelen
     ArrayList<BewegendeDelen> bewegendedelenarray = new ArrayList<BewegendeDelen>();
     Ruimteschip ruimteschip = new Ruimteschip();
    Raket raket = null;
     public void init()
          setBackground(Color.white);
          //nieuwepositielistener
          ActionListener nieuwePositieListener = new nieuwePositieListener();
          //interval van 1/4 seconde
          final int nieuwepositieDELAY = 250;
          //nieuwe positie timer
          Timer nieuwePositieTimer = new Timer(nieuwepositieDELAY, nieuwePositieListener);
        this.nieuwePositieTimer = nieuwePositieTimer;
          //start de nieuwe positietimer
          nieuwePositieTimer.start();
          //nieuwe alien listener
          ActionListener nieuweAlienListener = new nieuweAlienListener();
          //interval van 4 seconden
          final int nieuwealienDELAY = 4000;
          //nieuwe alientimer
          Timer nieuweAlienTimer = new Timer(nieuwealienDELAY, nieuweAlienListener);
        this.nieuweAlienTimer = nieuweAlienTimer;
          //start de nieuwe alientimer
          nieuweAlienTimer.start();
          //stop het spel listener
          ActionListener stopSpelListener = new stopSpelListener(15);
          //1 seconde interval
          final int stopspelDELAY = 1000;
          //nieuwe timer stop het spel
          stopSpelTimer = new Timer(stopspelDELAY, stopSpelListener);
          //start de timer
          stopSpelTimer.start();
          //bewegendedelenarray.add(alien);
          bewegendedelenarray.add(ruimteschip);
          //bewegendedelenarray.add(raket);
     //tekenen
     public void paint(Graphics g)
     {     //print uit bewegendedelenarray obj van het type BewegendeDelen
          for(BewegendeDelen obj : bewegendedelenarray)
          {     //teken de bewegende delen (ruimteschip, aliens en raketten)
               System.out.println(obj);
               obj.paint(g);
               //als teller op nul staat game over!
               if (count <= 0)
               g.drawString("Game over!", 250, 250);
               //laat de score zien als de teller op nul staat
               if (count <= 0)
               g.drawString("Je score is: " + score + "!", 250, 300);
     //pijltjes toetsen indrukken om te bewegen en spatie om te schieten
     public boolean keyDown(Event e, int key)
          {     //naar links
               if(key == Event.LEFT)
               {     if (ruimteschip.getX() > 10)
                         ruimteschip.beweegLinks();
                         System.out.println("links");
                         repaint();
               else
               //naar rechts
               if(key == Event.RIGHT)
               {     if (ruimteschip.getX() < 450)
                         ruimteschip.beweegRechts();
                         repaint();
               else
               //schieten
               if (key == 32)
                    raket = new Raket(ruimteschip.getX(), ruimteschip.getY());
                 bewegendedelenarray.add(raket);
                    raket.beweeg();
                    repaint();
          return true;
     //als er sprake is van een hit, roep dan de method aan
     public void controleerHit()
     {     //zolang er een raket is
               //vergelijk, voor ieder object, of een ander object dezelfde coordinaten heeft
               for(BewegendeDelen obj : bewegendedelenarray)
               //vergelijk de coordinaten
               if(raket != null && obj.checkHit(raket.getX(), raket.getY()))
                    //verwijderen, opnieuw tekenen en score ophogen
                    bewegendedelenarray.remove(obj);
                    bewegendedelenarray.remove(raket);
                    //raket = null;     
                    repaint();
                    score++;
     //iedere 1/4 seconden krijgen de aliens een nieuwe positie
     class nieuwePositieListener implements ActionListener
          public void actionPerformed(ActionEvent event)
          {   System.out.println("nieuwe pos");
             Random generator = new Random();
              //laat de objecten bewegen
                 for(BewegendeDelen obj : bewegendedelenarray)
                    obj.beweeg();
               repaint();
               controleerHit();
               /*if (raket.bestaatNog() )
                    bewegendedelenarray.remove(raket);        
                    raket = null;
     //om de vier seconden een nieuwe alien op het scherm
     class nieuweAlienListener implements ActionListener
          public void actionPerformed(ActionEvent event)
          {     //voeg een nieuw alien object aan de array toe
              System.out.println("nieuwe alien");
               bewegendedelenarray.add(new Alien());
               repaint();
     //na 15 seconden stopt het spel: Game Over!
     class stopSpelListener implements ActionListener
          public stopSpelListener(int initialCount)
               count = initialCount;
          public void actionPerformed(ActionEvent event)
        {   count--;  
            //als de teller op 0 staat is het spel voorbij
               if (count == 0)
                    nieuwePositieTimer.stop();
                  nieuweAlienTimer.stop();
                  stopSpelTimer.stop();
               else
                System.out.println("time left: " + count);
     //instantievariabelen
     private int count;
     private int score;
     private boolean geraakt;
}      import java.awt.*;
import java.awt.Graphics2D;
//superclass met gezamenlijke eigenschappen van de bewegende delen ruimteschip, alien en raket
public class BewegendeDelen
     public void paint(Graphics g)
    {      //weergave drawstring met x en y positie
         Graphics2D g2D = (Graphics2D)g;
        g.drawString(weergave, x, y);
     //zet de x positie
     public void setX(int xPos)
          x = xPos;
     //en y positie
     public void setY(int yPos)
          y = yPos;
     public void setWeergave(String deWeergave)
          weergave = deWeergave;
     public String getWeergave()
          return weergave;
     public int getX()
          return x;
     public int getY()
          return y;
     //beweegmethod rechts
     public void beweegRechts()
     {     //verschuif rechts
          x = x + 25;
    //beweegmethod links
     public void beweegLinks()
     {     //verschuif links
          x = x - 25;
     public void beweeg()
     public String toString()
        return weergave + ": (" + x + ", " + y +")";
     //geef de breedte terug
     public int getWidth()
          return width;
     public boolean checkHit(int rx, int ry)
               return true;
     public boolean bestaatNog()
          return true;
     //instantievariabelen
     public int x;
     public int y;
     public String weergave;
     public int width;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics2D;
//subklasse van "bewegendedelen" die eigenschappen ervan erft, en met beweegmethods
public class Ruimteschip extends BewegendeDelen
     public Ruimteschip()
          weergave = "<<=>>";
        x = 250;
         y = 500;
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
//de alien class
public class Alien extends BewegendeDelen
     public Alien()
          weergave = "^^^";
          y = 25;
     public void beweeg()
          x= x+10;
     public boolean checkHit(int rx, int ry)
               if((rx >= getX() && rx <= (x+weergave.length()*10)) && ry == getY())
                    geraakt = true;
          return false;
     public boolean geraakt;
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
public class Raket extends BewegendeDelen
     public Raket(int x, int y)
         weergave = "|";
         setX(x+17);
         setY(y);
     //schietmethod, verticaal omhoog bewegen
     public void beweeg()
          y = y - 40;
     //een lege string als weergave
     public void verwijder()
          weergave = "";
     //als de raket uit het scherm is dan bestaat hij niet meer
/*     public boolean bestaatNog()
          if (getY()<0)
          {return false;}
          else return  true;
} Edited by: Roddy on Oct 22, 2008 4:28 AM

Roddy wrote:
Hi!
My awful version of space invaders is almost ready. I only have problems programming the method where I check whether a rocket hits an alien. This method is called 'controleerHit' in Spel.
Thanks for your help!And what is wrong with it? Have you tried putting some debug code in the method to see what is going on?

Similar Messages

  • Need help making pace invaders in java

    So here is my code:
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.*;
    import javax.swing.JPanel;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class invaders extends Canvas {
    public static final int Width = 800;
    public static final int Height = 600;
    public invaders() {
    JFrame openspace = new JFrame("Space Invaders");
    JPanel window = (JPanel)openspace.getContentPane();
    setBounds(0,0,Width,Height);
    window.setPreferredSize(new Dimension(Width,Height));
    window.setLayout(null);
    window.add(this);
    openspace.setBounds(0,0,Width,Height);
    openspace.setVisible(true);
    openspace.addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void paint(Graphics graph) {
    // graph.setColor(Color.red);
    // graph.fillOval( Width/2-10, Height/2-10,20,20);
    // spacealien = loadImage("spaceAlien.jpg");
    // graph.drawImage(spaceAlien, 50, 50, this);
    public static void main(String[] args) {
    invaders spaceinvaders = new invaders();
    I am trying to add pictures into the JFrame but I don't know how. I am following this tutorial http://www.planetalia.com/cursos/Java-Invaders/JAVA-INVADERS-04.tutorial but I get confused when they talk about how to add in an image.
    This is their Code:
    1 package version04;
    2 /**
    3 * Curso B?sico de desarrollo de Juegos en Java - Invaders
    4 *
    5 * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
    6 *
    7 * http://www.planetalia.com
    8 *
    9 */
    10
    11
    12 import java.awt.Canvas;
    13 import java.awt.Dimension;
    14 import java.awt.Graphics;
    15 import java.awt.event.WindowAdapter;
    16 import java.awt.event.WindowEvent;
    17 import java.awt.image.BufferedImage;
    18 import java.net.URL;
    19
    20 import javax.imageio.ImageIO;
    21 import javax.swing.JFrame;
    22 import javax.swing.JPanel;
    23
    24 public class Invaders extends Canvas {
    25 public static final int WIDTH = 800;
    26 public static final int HEIGHT = 600;
    27
    28
    29 public Invaders() {
    30 JFrame ventana = new JFrame("Invaders");
    31 JPanel panel = (JPanel)ventana.getContentPane();
    32 setBounds(0,0,WIDTH,HEIGHT);
    33 panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
    34 panel.setLayout(null);
    35 panel.add(this);
    36 ventana.setBounds(0,0,WIDTH,HEIGHT);
    37 ventana.setVisible(true);
    38 ventana.addWindowListener( new WindowAdapter() {
    39 public void windowClosing(WindowEvent e) {
    40 System.exit(0);
    41 }
    42 });
    43 }
    44
    45 public BufferedImage loadImage(String nombre) {
    46 URL url=null;
    47 try {
    48 url = getClass().getClassLoader().getResource(nombre);
    49 return ImageIO.read(url);
    50 } catch (Exception e) {
    51 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
    52 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
    53 System.exit(0);
    54 return null;
    55 }
    56 }
    57
    58
    59 public void paint(Graphics g) {
    60 BufferedImage bicho = loadImage("res/bicho.gif");
    61 g.drawImage(bicho, 40, 40,this);
    62 }
    63
    64 public static void main(String[] args) {
    65 Invaders inv = new Invaders();
    66 }
    67 }
    68
    I know there must be an easier way. Please help, thanks!!!!

    One way to add an image to a user interface is to use a JLabel with an ImageIcon: [http://java.sun.com/docs/books/tutorial/uiswing/components/label.html]

  • Help! trying to create 'space invaders'

    hi. im a high school student with a little knowledge of java. im am currently working on a class assignment where each student has to create their own program. i decided to create the classic game of 'Space Invaders'. But i have a problem; i can't figure out how i will get the characters to move.
    does anyone if there is a method that will allow the user to move a character? for example, in C++ there is a conio.h library that has a goto(x,y) function. is there one for java as well? thanks alot!

    This is another way
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Si extends JFrame
         Timer  ta;
         myView view = new myView();
    public Si() 
         setBounds(3,10,765,350);
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         getContentPane().add("Center",view);
         setVisible(true);
         ta = new Timer(45, new ActionListener()
         {     public void actionPerformed(ActionEvent e)
                   view.move();
         ta.start();
    public class myView extends JComponent 
         Point invs[]   = new Point[15];
         Color invc[]   = new Color[15];
         Color  color[] = new Color[]{
                        Color.blue,   Color.cyan, Color.green, Color.magenta,
                    Color.orange, Color.pink, Color.red,   Color.yellow};
    public myView()
         for (int p=0; p < invs.length; p++)
              int x = (int)(Math.random()*600)+33;
              int y = (int)(Math.random()*200)+33;
              invs[p] = new Point(x,y);
              int c = (int)(Math.random()*8);
               invc[p] = color[c];
    public void move()
         for (int p=0; p < invs.length; p++)
              repaint(invs[p].x-1,invs[p].y-1,20,18);
              int x = (int)(Math.random()*3)-1;
              int y = (int)(Math.random()*3)-1;
              invs[p].translate(x,y);
              repaint(invs[p].x-1,invs[p].y-1,20,18);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);          
         for (int p=0; p < invs.length; p++)
              g.setColor(invc[p]);
              g.fillOval(invs[p].x,invs[p].y,17,13);
    public static void main (String[] args) 
         new Si();
    }      Noah

  • Space invaders! I need some help...!

    Hello,
    i'm trying to program a very simple version of space invaders. I'm drawing my moving objects (spaceship, rockets, aliens) with drawstring but I'm getting these compiling error: illegal start of expression.
    Also I want to move the spaceship with translate is this OK to do so!?
    Can somebody help me? Thanks for your help!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.Graphics2D;
    //in deze klasse teken ik het ruimteschip en kan het links/rechts bewegen
    public class Ruimteschip
         //ruimteschip
         Ruimteschip roderikschip = new Ruimteschip();
         public void paint(Graphics ruimteschip)
    {      //Ruimteschip weergeven
         Graphics2D ruimteschip2D = (Graphics2D)ruimteschip;
    String ruimteschip = "ruimteschip";
    ruimteschip2D.drawString("ruimteschip", x, y,);
         //beweegmethod
         public void beweegRechts()
         {     //teken opnieuw 1 coordinaat rechts
              roderikschip.translate(1, 0);
              ruimteschip2D.drawString("ruimteschip", x, y);
    //beweegmethod
         public void beweegLinks()
         {     //teken opnieuw 1 coordinaat links
              roderikschip.translate(-1, 0);
              ruimteschip2D.drawString("ruimteschip", x, y);
    }

    Hi and thanks for your replies.
    I know drawString isn't the most beautiful way, but I'm making this game for an assignment, and I have to use drawString.
    Still i'm getting "illegal start of expression" in my paint method...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.Graphics2D;
    //in deze klasse teken ik het ruimteschip en kan het links/rechts bewegen
    public class Ruimteschip
         //ruimteschip
            Ruimteschip ruimteschip = new Ruimteschip();
         public void paint(Graphics ruimteschip)
        {      //Ruimteschip weergeven
             Graphics2D ruimteschip2D = (Graphics2D)ruimteschip;
            String s = "ruimteschip";
            *ruimteschip2D.drawString(s, x, y,);*
         //beweegmethod
         public void beweegRechts()
         {     //teken opnieuw 1 coordinaat rechts
              s.translate(1, 0);
              ruimteschip.drawString(s, x, y);
        //beweegmethod
         public void beweegLinks()
         {     //teken opnieuw 1 coordinaat links
              s.translate(-1, 0);
              ruimteschip.drawString(s, x, y);
    } Edited by: Roddy on May 1, 2008 8:28 AM

  • Cannot assign an empty string to a parameter with JDBC type VARCHAR

    Hi,
    I am seeing the aforementioned error in the logs. I am guessing its happening whenever I am starting an agent instance in PCo. Can somebody explain whats going on?
    Regards,
    Chanti.
    Heres the complete detail from logs -
    Log Record Details   
    Message: Unable to retreive path for , com.sap.sql.log.OpenSQLException: Failed to set the parameter 1 of the statement >>SELECT ID, PARENTID, FULLPATH, CREATED, CREATEDBY, MODIFIED, MODIFIEDBY, REMOTEPATH, CHECKEDOUTBY FROM XMII_PATHS WHERE FULLPATH =  ?  <<: Cannot assign an empty string to a parameter with JDBC type >>VARCHAR<<.
    Date: 2010-03-12
    Time: 11:32:37:435
    Category: com.sap.xmii.system.FileManager
    Location: com.sap.xmii.system.FileManager
    Application: sap.com/xappsxmiiear

    Sounds like a UI browsing bug (when no path is selected from a catalog tree folder browser) - I would suggest logging a support ticket so that it can be addressed.

  • Problems with string comparison and\or If statement

    Right now I'm trying to make a program that will look into all of my music folders, and rename the .mp3 files to a format i want, based on the id3 tags. The program so far looks in all of the folders I want it to, but I get stuck when I need to check if the files are .mp3 files or not. Here is my code so far:
    package fileRenamer;
    import java.io.File;
    public class FileRenamer {
    public static void main(String[] argv) {
         File artistsFolders = new File("F:/Music (MP3)");
         File[] artists = artistsFolders.listFiles();
         for(int i = 0; i < artists.length; i++){
              if(artists.isFile()) {
                   System.out.println(artists[i].getName());
         } else if (artists[i].isDirectory()) {
              System.out.println(artists[i].getName());
              File albumsFolders = new File("F:/Music (MP3)/"+artists[i].getName());
              File[] albums = albumsFolders.listFiles();
              for(int a = 0; a < albums.length; a++){
                   if(albums[a].isFile()) {
                        System.out.println("-" + albums[a].getName());
                   } else if (albums[a].isDirectory()) {
                        System.out.println("-" + albums[a].getName());
                   File songsFolders = new File("F:/Music (MP3)/"+artists[i].getName()+"/"+albums[a].getName());
                   File[] songs = songsFolders.listFiles();
                   for(int s = 0; s < songs.length; s++){
                        if(songs[s].isFile()) {
                             int dotPos = songs[s].getName().toString().lastIndexOf(".");
                             String extension = songs[s].getName().toString().substring(dotPos);
                             System.out.println(extension);
                             if(extension == ".mp3"){
                                  System.out.println("--" + songs[s].getName());
                   } else if (songs[s].isDirectory()) {
                             System.out.println("--" + songs[s].getName());
    When I test the code, the line System.out.println(extension); prints .mp3 into the console for all of the .mp3 files. Whatever I try, the if(extension == ".mp3") never seems to declare the two equal. If anyone knows what my problem is, I greatly appreciate the advice and help.
    Thanks in Advance,
    James

    Pojo226 wrote:
    I just tried that and it worked perfectly. Thanks.You're welcome.

  • Oracle, Null and empty Strings

    Currently I'm facing problems with a class, which contains a String, which
    is set to "" (empty String).
    When the class is persistent, oracle writes null to the table column
    (which seems to be common oracle behaviour) and when retrieving the class,
    the field is set to null as well, giving me a lot of null-pointer
    exceptions.
    Anyway ... I can cope with that (just a lot of extra work)
    far worse is the problem, wenn searching objects, that have this field set
    to "" oder null.
    Oracle can't find the records because JDO creates Querys "where
    string=null" or "where string=''" , where oracle expects "where string is
    null" to find the records.
    Is there a workaround or solution ?

    Yeah, that would work as well, thx, but since I have to cope with
    null-Strings now everywhere in my program, it doesn't hurt just to forbid
    empty strings on the program side.
    In future times I'll test on Oracle first, then porting to DB/2 - this way
    I suppose work is far less to garant compability.
    Nevertheless ... having to set the bankcode into quotes is a kodo bug in
    my opinion.
    Kodo knows the type of classfields (in this case string) and shouldn't
    send the parameter as a BigDecimal to the database.
    Given that, and having only bankcodes of null (only neccesary when using
    Oracle), the method would look like:
    public Collection getAccounts (String bankCode)
    throws Exception
    return getAccounts (Account.class, "bankcode=="+bankcode);
    which is how a transparent persistent layer, um, should be , um , I mean
    ... just transparent ;-D
    Marc Prud'hommeaux wrote:
    Stefan-
    Couldn't you just do something like:
    public Collection getAccounts (String bankCode)
    throws Exception
    String filter;
    if (bankCode == null || bankCode.length () == 0)
    filter = "(bankCode == null || bankCode == "")";
    else
    filter = "bankCode == "" + bankCode + """;
    return getAccounts (Account.class, filter);
    If I understand the problem correctly, this should work for all the
    databases.
    In article <[email protected]>, Stefan wrote:
    What operations are you performing to cause this SQL to be issued? You
    say you are having trouble removing objects, but this is clearly not a
    DELETE statement. Is this the SQL that is issued when looking up
    objects by identity?I'm not removing objects, I was removing just quotes from parameters ;-)
    A string column... is it also represented as a string field in your class?Yeah ... just to give you an impression of the code:
    First we have a class, representing a bank account:
    public class Account {
    private AccountMgr myAccountMgr;
    private String bankCode;
    private String id;
    Note, that in nearly all cases bankCode will be a number or null.
    I have a second class "AccountMgr", which does all of the persistant stuff
    (seaching, making persistent etc.)
    This class has two methods, one versatile (protected) to retrieve accounts
    by a given filterString and one who just returns accounts by bankCode,
    building the expected filterstring. Here is my current working version:
    public class AccountMgr {
    public Collection getAccounts(String bankCode) throws Exception {
    if (bankCode!=null) {
    if (bankCode.equals("")) {
    throw new Exception("check code, bankCode='' not allowed to get
    same behavior from DB2 and Oracle");
    // if set, quote the bankCode
    bankCode="""+bankCode+""";
    return getAccounts(Account.class,"bankCode=="+bankCode);
    protected Collection getAccounts(Class accountClass, String filterAdd)
    throws Exception {
    PersistenceManager pm = MyHelper.getPersistenceManager();
    String filter="";
    if (filterAdd!=null && !filterAdd.trim().equals("")) {
    filter+=filterAdd + " && ";
    filter += "myAccountMgr==_accMgr";
    Query query = pm.newQuery(accountClass, filter);
    query.declareParameters("AccountMgr _accMgr");
    return (Collection) query.execute(this);
    As you can see, in the first method I have to set the bankCode into
    quotes, when it's not null.
    This is because otherwise a filter like "bankCode=1234" will be translated
    in a way, where 1234 is send as a BigDecimal to the database:
    [...] executing statement <4239745>: (SELECT [...] FROM JDO_ACCOUNT t0
    WHERE t0.BANKCODE = ? : [reused=1;params={(BigDecimal) 1234}]
    Marc Prud'hommeaux [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • NULL and Empty String

    Hi There,
    As far as I know, Null is not the same as an empty string; however, when I try this out, I get some unexpected results (well, at least unexpected for my liking):
    SQL> CREATE TABLE TS (MID NUMBER,
      2  MDESC VARCHAR2(20) DEFAULT '' NOT NULL);
    Table created.
    SQL> INSERT INTO TS VALUES(1,'');
    INSERT INTO TS VALUES(1,'')
    ERROR at line 1:
    ORA-01400: cannot insert NULL into ("TT"."TS"."MDESC")So, according to the above scenario, I can't insert an empty string!! However, an empty string is a valid string that doesn't have tuples/data!!
    How come Oracle translates the null string '' as NULL?
    Thanks

    William Robertson wrote:
    There is a special case to do with CHAR values, whereby '' counts as a string and so gets blank-padded, whereas NULL does not.Are you referring to:
    SQL> DECLARE
      2      flag CHAR(2);
      3      PROCEDURE check_null (p_flag IN CHAR)
      4      IS
      5      BEGIN
      6        IF p_flag = '  '
      7        THEN
      8          dbms_output.put_line ('flag is equal to ''  ''');
      9        ELSIF p_flag IS NULL
    10        THEN
    11          dbms_output.put_line ('flag is null');
    12        ELSE
    13          dbms_output.put_line ('other');
    14        END IF;
    15      END;
    16    BEGIN
    17      flag := '';
    18      check_null (flag);
    19      flag := NULL;
    20      check_null (flag);
    21    end;
    22  /
    flag is equal to '  '
    flag is null
    PL/SQL procedure successfully completed.
    SQL> alter session set events '10932 trace name context forever, level 16384';
    Session altered.
    SQL> DECLARE
      2      flag CHAR(2);
      3      PROCEDURE check_null (p_flag IN CHAR)
      4      IS
      5      BEGIN
      6        IF p_flag = '  '
      7        THEN
      8          dbms_output.put_line ('flag is equal to ''  ''');
      9        ELSIF p_flag IS NULL
    10        THEN
    11          dbms_output.put_line ('flag is null');
    12        ELSE
    13          dbms_output.put_line ('other');
    14        END IF;
    15      END;
    16    BEGIN
    17      flag := '';
    18      check_null (flag);
    19      flag := NULL;
    20      check_null (flag);
    21    end;
    22  /
    flag is null
    flag is null
    PL/SQL procedure successfully completed.
    SQL> SY.
    P.S. Don't ask me why normal (or at least consistent) behavior is not the default.

  • Null and empty string not being the same in object?

    Hello,
    I know that null and empty string are interpreted the same in oracle.
    However I discovered the strange behaviour concerning user defined objects:
    create or replace
    TYPE object AS OBJECT (
    value VARCHAR2(2000)
    declare
    xml xmltype;
    obj object;
    begin
    obj := object('abcd');
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := '';
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := null;
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    end;
    When creating xml from object, all not-null fields are transformed into xml tag.
    I supposed that obj.value being either '' or null will lead to the same result.
    However this is output from Oracle 9i:
    <OBJECT_ID><VALUE>abcd</VALUE></OBJECT_ID>
    <OBJECT_ID><VALUE></VALUE></OBJECT_ID>
    <OBJECT_ID/>
    Oracle 10g behaves as expected:
    <OBJECT><VALUE>abcd</VALUE></OBJECT>
    <OBJECT/>
    <OBJECT/>
    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?

    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?A lot of "fixes" were done, relating to XML in 10g and the XML functionality of 9i was known to be buggy.
    I think you can safely assume that null and empty strings are treated the same by Oracle regardless. If you're using anything less than 10g, it's not supported any more anyway, so upgrade. Don't rely on any assumptions that may appear due to bugs.

  • Difference in Null and Empty String

    Hi,
    I have been wondering about the difference between Null and Empty String in Java. So I wrote a small program like this:
    public class CompareEmptyAndNullString {
         public static void main(String args[]) {
              String sNull = null;
              String sEmpty = "";
              try {
                   if (sNull.equalsIgnoreCase(sEmpty)) {
                        System.out.println("Null and Empty Strings are Equal");
                   } else {
                        System.out.println("Null and Empty Strings are Equal");
              } catch (Exception e) {
                   e.printStackTrace();
    This program throws Exception: java.lang.NullPointerException
         at practice.programs.CompareEmptyAndNullString.main(CompareEmptyAndNullString.java:10)
    Now if I change the IF Clause to if (sEmpty.equalsIgnoreCase(sNull)) then the Program outputs this: Null and Empty Strings are Equal
    Can anyone explain why this would happen ?
    Thanks in Advance !!

    JavaProwler wrote:
    Saish,
    Whether you do any of the following code, the JUnit Test always passes: I mean he NOT Sign doesnt make a difference ...
    assert (! "".equals(null));
    assert ("".equals(null));
    You probably have assertions turned off. Note the the assert keyword has nothing to do with JUnit tests.
    I think that older versions of JUnit, before assert was a language keyword (which started in 1.4 or 1.5), had a method called assert. Thus, if you have old-style JUnit tests, they might still compile, but the behavior is completely different from what it was in JUnit, and has nothing to do with JUnit at all.
    If you turn assertions on (-ea flag in the JVM command line, I think), the second one will throw AssertionError.

  • SSRS Report Returning Double Quote string from a Single Quote String

    Hi, I'm getting weird thing in resultset from SSRS report when executed. When I pass parameter to a report, which passes String that has single quote value to a split function , it returns rows with double quote. 
    For example  following string:
    'N gage, Wash 'n Curl,Murray's, Don't-B-Bald
    Returns: 
    ''N gage, Wash ''n Curl,Murray''s, Don''t-B-Bald
    through SSRS report.
    Here is the split function Im using in a report.
    CREATE Function [dbo].[fnSplit] (
    @List varchar(8000), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(8000) NULL 
    As 
    Begin 
    Declare @item varchar(4000), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final delimiter 
    Select @List = @List + @Delimiter -- get position of first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List) - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    FYI: I'm getting @List value from a table and passing it as a string to split function. 
    Any help would be appreciated!
    ZK

    Another user from TSQL forum posted this code which is returning the same resultset but when I execute both codes in SQL server it works and return single quote as expected.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8d5c96f5-c498-4f43-b2fb-284b0e83b205/passing-string-which-has-single-quote-rowvalue-to-a-function-returns-double-quoate?forum=transactsql
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    ZK

  • How can I convert an int to a string?

    Hi
    How can I convert an int to a string?
    /ad87geao

    Here is some the code:
    public class GUI
        extends Applet {
      public GUI() { 
        lastValue = 5;
        String temp = Integer.toString(lastValue);
        System.out.println(temp);
        showText(temp);
      private void showText(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            tArea2.setText(text + "\n");
    }

  • No calendar change for a single event in a recurrring string of events

    Why won't iCal allow me to change the calendar for a single event in a string of recurring events? Why am I not allowed this, but can change other details and even get prompted whether I want these changes to take effect over the single event or all the recurring events????
    Could this be implemented in a future version of iCal???
    Thanks.

    How are you making the .ics file? What value has the METHOD: entry?
    AK

  • How do i find the length of a string??

    trying to use the substring, I know the beginIndex (in my case 10), but the string will vary in size and so i need to find the last character and set it as the endIndex, how do i do this?
    public String substring(int beginIndex,
    int endIndex)Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
    Examples:
    "hamburger".substring(4, 8) returns "urge"
    "smiles".substring(1, 5) returns "mile"
    Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.
    Returns:
    the specified substring.

    Hi
    To substring the string where u know the begin index and want to extract till the end use the following function from the String class of the java.lang package
    String substring(int beginindex);
    String test = "Hello";
    String xx = test.substring(1);
    The Value stored in xx will be ello
    This is in case u need till the end of the String
    If wanna skip the last character u can
    use
    String substring(int beginindex,int endindex);
    String test = "Hello";
    String xx = test.substring(1,test.length()-1);
    The Value stored in xx will be ell

  • Reading a string one character at a time

    Hi,
    I'm hoping you use SmallBasic for year 10 exam students at my school.  But, I have found a problem I cannot solve.
    I need to be able to read one character at a time from a string (txt file) and convert each char to its ACSII code.
    How do to I read one char at a time from a string to enable processing?
    Thanks for your help.
    Baz 

    Here is an over the top solution that will display the Hex value of the character codes of every character in the file.
    TextWindow.Write("Enter full file name: ")
    filnam = TextWindow.Read()
    contents = File.ReadContents(filnam) 'read the entire file
    TextWindow.Clear()
    TextWindow.WriteLine("File Name: " + filnam)
    TextWindow.WriteLine("Offset: 0")
    col = 0
    row = 5
    TextWindow.CursorLeft = col
    TextWindow.CursorTop = row
    For i= 1 To Text.GetLength(contents)
    ch = Text.GetSubText(contents, i,1)
    chVal = Text.GetCharacterCode(ch)
    ConvertToHex()
    TextWindow.CursorLeft = col
    If chVal < 32 Then
    TextWindow.Write(".")
    Else
    TextWindow.Write(ch)
    EndIf
    TextWindow.CursorLeft = 20 + 2 + (col * 3)
    TextWindow.Write(Text.GetSubText(hexstr,1,2))
    col = col + 1
    If col = 8 Then
    col = col + 1
    EndIf
    If col > 16 Then
    col = 0
    row = row + 1
    If row > 20 then
    TextWindow.CursorTop = 23
    TextWindow.CursorLeft = 25
    TextWindow.Write("< < < Press ENTER to Continue > > >")
    TextWindow.Read()
    TextWindow.Clear()
    TextWindow.WriteLine("File Name: " + filnam)
    TextWindow.WriteLine("Offset: " + i)
    row = 5
    EndIf
    TextWindow.CursorTop = row
    EndIf
    EndFor
    TextWindow.WriteLine("")
    TextWindow.WriteLine("")
    Sub ConvertToHex
    HexValue[0] = "0"
    HexValue[1] = "1"
    HexValue[2] = "2"
    HexValue[3] = "3"
    HexValue[4] = "4"
    HexValue[5] = "5"
    HexValue[6] = "6"
    HexValue[7] = "7"
    HexValue[8] = "8"
    HexValue[9] = "9"
    HexValue[11] = "A"
    HexValue[12] = "B"
    HexValue[13] = "C"
    HexValue[14] = "D"
    HexValue[15] = "E"
    val = chVal
    hexstr = "h" 'Need to force Small basic to concatenate rather than add
    While val > 0
    hexPos = Math.Remainder(val, 16)
    hexstr = HexValue[hexPos] + hexstr
    val = Math.Floor(val / 16)
    EndWhile
    For hi = Text.GetLength(hexstr) To 2
    hexstr = "0" + hexstr
    EndFor
    EndSub
    Enjoy!

Maybe you are looking for

  • Offline approval

    Hello We all know that during offline approval of shopping carts the approver used to get a failure mail if there is some error . Some cases even after approval the approval status is not getting updated which is still showing awaiting approval where

  • FSL-00009  System call failed

    Hi experts,     When I install additonal dialog instance , the system issue the error: INFO       2014-12-23 16:34:04.436 [syuxcfile.cpp:218]            CSyFileImpl::removeEx(ISyFSErrorHandler * pErrorHandler)            lib=syslib module=syslib Remo

  • HELP!! Nokia N95 restarting !! and more!!

    Okay im now on my 3rd Nokia N95 from the 02 network the first 2 handsets had high pitch whining noise and awful sliders which were wobbling on the right hand side, appaulling workmanship, i dont even know how they were allowed to leave the Nokia Fact

  • Conditional build tags and numbered lists

    Is there a way to get numbered lists to automatically update when conditional tags are used? For example, only step 6 of a 10 step list is needed for 1 of 4 products. However, when I preview the content for the 3 of 4 products that do not require tha

  • It will not launch on my PPC Mac running OS 10.5.8

    Trying to run FireFox 4.0b10 on my PPC G5 Mac running OS 10.5.8. Will it only run on an Intel Mac? Keep getting the error "Will not run on this machine".