NullPointerException on a method declaration?

Hi all,
I'm not sure whether I should be posting this here on on the app server board.
But anyway, I have an ADF application (with ADF Faces) that works fine in JDev 10.1.3, and after some difficulty, I've managed to get it deployed, so that the first page comes up properly in a browser.
When I click on a link in my navigation tree, however, I get an error in the method called by the CommandLink in the tree node. Here's what it is:
javax.faces.FacesException: #{homeBean.treeNavigate}: javax.faces.el.EvaluationException
Caused by [at the bottom]: java.lang.NullPointerException
at mypackage.BasePage.TreeNavigate (BasePage.java:53)
So OK, for some reason my code is firing a null pointer exception in the deployed version. Let's see what it is by checking BasePage.java, line 53:
53) public String treeNavigate() {
A method declaration. That shouldn't be able to throw a NullPointerException, or indeed any other runtime error, should it?
Can anyone shed some light about what might be going on here?
Thanks much,
Avrom

public void drawPictures(int size, Graphics page)
          page.drawImage (board, 0, 0, 720, 567, this);
public void paint (Graphics page)
          drawPictures (APPLET_WIDTH, page);
private final int APPLET_WIDTH = 720;
board = getImage (getDocumentBase(), "board.jpg"); //inside my init() methodThanks for the quite response. I looked at my code with your suggestions and came up with this:
If I take away my "paint" method, the buttons have no problems, but, of course, no picture comes up. Any ideas?
I was also throw out the fact that this is my first time with GUIs. My teacher saved them to the end last year, got lazy, and then never did them. So if I am using horrible self-taught practices, it would be awesome if you can let me know, so I can improve. Thanks.
Edited by: 7sunami on Feb 22, 2009 6:00 PM

Similar Messages

  • ClassCastException in method declaration in JSP page??

    i keep getting this ClassCastException in my jsp page. The line that
    is apparently the problem is the <%! where the method declaration
    starts. I can't seem to figure out why this is happening, can someone
    please help? Here is the full code:
    java.lang.ClassCastException
         at quickfix0itm_0submit__jsp.addUpdate(/epsc/quickfix_itm_submit.jsp:25)
         at quickfix0itm_0submit__jsp._jspService(/epsc/quickfix_itm_submit.jsp:165)
         at com.caucho.jsp.JavaPage.service(JavaPage.java:75)
         at com.caucho.jsp.Page.subservice(Page.java:506)
         at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:182)
         at com.caucho.server.http.Invocation.service(Invocation.java:315)
         at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
         at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:344)
         at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)
         at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
         at java.lang.Thread.run(Thread.java:534)
    <%
    if ( (session.getAttribute("setID") == null ) || ( !session.getAttribute("setID").equals(session.getId()) ))
            out.write("You are either not logged in or your session has timed out due to inactivity.<BR>"
                    + "Please <a href=\"index.jsp\">return to the login screen</a> and login again<BR><BR>");
    else
    %>
    <%@ page language=java %>
    <%@ page import='java.sql.*' %>
    <%@ page import='javax.sql.*' %>
    <%@ page import='javax.naming.*' %>
    <%@ page import='java.io.*' %>
    <%@ page import='java.util.Hashtable' %>
    <%@ page import='java.util.Vector' %>
    <%@ page import='java.util.Enumeration' %>
    <%@ page import='java.util.Calendar' %>
    <%@ page import='java.util.GregorianCalendar' %>
    <%!
    private void addUpdate(String[] tmpP, String[] UIDs, String curName, String colName, String lastIdx, Hashtable uid_updates)
         if (curName.equals(colName))
              for (int c = 0; c < UIDs.length; c++)
                   Object[] tmp = (Object[])uid_updates.get(UIDs[c]);
                   Vector colNames = new Vector();
                   Vector colValues = new Vector();
                   if (tmp == null)
                        tmp = new Object[2];
                   else
                        colNames = (Vector)tmp[0];
                        colValues = (Vector)tmp[1];
                   String updateVal = tmpP[0];
                   colNames.add(curName);
                   colValues.add(updateVal);
                   tmp[0] = colNames;
                   tmp[1] = colValues;
                   uid_updates.remove(UIDs[c]);
                   uid_updates.put(UIDs[c], tmp);
         else
              int uidIdx = curName.lastIndexOf(lastIdx);
              String uidcode = curName.substring(uidIdx + 1);
              Object[] tmp = (Object[])uid_updates.get(uidcode);
              Vector colNames = new Vector();
              Vector colValues = new Vector();
              if (tmp == null)
                   tmp = new Object[2];
              else
                   colNames = (Vector)tmp[0];
                   colValues = (Vector)tmp[1];
              //String[] tmpP = request.getParameterValues(curName);
              String updateVal = tmpP[0];
              colNames.add(colName);
              colValues.add(updateVal);
              tmp[0] = colNames;
              tmp[1] = colValues;
              uid_updates.remove(uidcode);
              uid_updates.put(uidcode, tmp);
    %>
    <%
    String ss = "0";
    String force_noon = "0";
    String qfix_duration = "2";
    int qfixd = 2;
    String mod_keys = "";
    String[] mktmp = request.getParameterValues("mod_keys");
    if (mktmp == null)
         out.print("Error! Please go back and try again.");
    else
         mod_keys = mktmp[0];
    Hashtable uid_updates = new Hashtable();
    String[] UIDs = new String[1];
    if (mod_keys.equals("1"))
         UIDs = request.getParameterValues("UID");
         for (int storeUIDs = 0; storeUIDs < UIDs.length; storeUIDs++)
              Vector tmp = new Vector();
              uid_updates.put(UIDs[storeUIDs], tmp);
    Enumeration cols = request.getParameterNames();
    while (cols.hasMoreElements())
         String curName = (String)cols.nextElement();
         if (curName.indexOf("BusName") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "BusName", "e", uid_updates);
         else if (curName.equals("ss"))
              String[] asdfadf  = request.getParameterValues(curName);
              if (asdfadf != null)
                   ss = "1";
              else
                   ss = "0";
         else if (curName.equals("force_noon"))
              String[] asdfadf  = request.getParameterValues(curName);
              force_noon = asdfadf[0];
         else if (curName.equals("qfix_duration"))
              String[] asdfadf  = request.getParameterValues(curName);
              qfix_duration = asdfadf[0];
              qfixd = Integer.parseInt(qfix_duration);
         else if (curName.indexOf("DisplayLine") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DisplayLine", "e", uid_updates);
         else if (curName.indexOf("CityName") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "CityName", "e", uid_updates);
         else if (curName.indexOf("PAC") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "PAC", "C", uid_updates);
         else if (curName.indexOf("ProvDisp") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "ProvDisp", "p", uid_updates);
         else if (curName.indexOf("TeleNum") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "TeleNum", "m", uid_updates);
         else if (curName.indexOf("ProvCode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "ProvCode", "e", uid_updates);
         else if (curName.indexOf("Dircode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "Dircode", "e", uid_updates);
         else if (curName.indexOf("Hdgcode") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "Hdgcode", "e", uid_updates);
         else if (curName.indexOf("EMail") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EMail", "l", uid_updates);
         else if (curName.indexOf("URL") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "URL", "L", uid_updates);
         else if (curName.indexOf("DispAd") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DispAd", "d", uid_updates);
         else if (curName.indexOf("TOPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "TOPlus", "s", uid_updates);
         else if (curName.indexOf("EStore") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EStore", "e", uid_updates);
         else if (curName.indexOf("HSLINE_EN") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "HSLINE_EN", "N", uid_updates);
         else if (curName.indexOf("HSLINE_FR") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "HSLINE_FR", "R", uid_updates);
         else if (curName.indexOf("MtlPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "MtlPlus", "s", uid_updates);
         else if (curName.indexOf("CalPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "CalPlus", "s", uid_updates);
         else if (curName.indexOf("EdmPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "EdmPlus", "s", uid_updates);
         else if (curName.indexOf("VanPlus") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "VanPlus", "s", uid_updates);
         else if (curName.indexOf("DEALER_LOCATOR") != -1)
              addUpdate(request.getParameterValues(curName), UIDs, curName, "DEALER_LOCATOR", "R", uid_updates);
    long curTime = System.currentTimeMillis();
    long monthMS = 2629743832L;
    long expLength = monthMS * qfixd;
    long expTime = curTime + expLength;
    java.sql.Date d1 = new java.sql.Date(System.currentTimeMillis());
    String Start_Date = d1.toString();
    d1 = new java.sql.Date(expTime);
    String Expiry_Date = d1.toString();
    Context env1 = (Context) new InitialContext().lookup("java:comp/env");
    DataSource source1 = (DataSource) env1.lookup("jdbc/epsc");
    Connection conn1 = source1.getConnection();
    String Pub_ID = "";
    try {
         Enumeration uidKeys = uid_updates.keys();
         while (uidKeys.hasMoreElements())
              String Unique_ID = (String)uidKeys.nextElement();
              Object[] updateData = (Object[])uid_updates.get(Unique_ID);
              Vector colNames = (Vector)updateData[0];
              Vector colValues = (Vector)updateData[1];
              String selectRecord = "SELECT * from epsc_ypca WHERE Unique_ID='" + Unique_ID + "';";
              Statement getRecord = conn1.createStatement();
              ResultSet returned = getRecord.executeQuery(selectRecord);
              Pub_ID = returned.getString("Pub_ID");
              boolean createDelete = false;
              String updateString = "";
              for (int b = 0; b < colNames.size(); b++)
                   if (b != 0)
                        updateString = updateString + ", ";
                   String colName = (String)colNames.get(b);
                   String colVals = (String)colValues.get(b);
                   if (colName.equals("BusName") || colName.equals("DisplayLine") || colName.equals("ProvDisp") || colName.equals("CityName") || colName.equals("PAC") || colName.equals("TeleNum"))
                        if (!((returned.getString(colName)).equals(colVals)))
                             createDelete = true;
                   updateString = updateString + colName + "='" + colVals + "'";
              if (createDelete)
                   //create delete
                   String delFromQuickfixes = "DELETE FROM epsc_quickfixes WHERE Start_Date='" + Start_Date + "' AND Pub_ID='" + Pub_ID + "' AND QFix_Type='2';";
                   Statement delItm = conn1.createStatement();
                   delItm.execute(delFromQuickfixes);
                   String insertQfixDel = "INSERT INTO epsc_quickfixes SELECT *, '0' as UID, '" + Start_Date + "' as Start_Date, '" + Expiry_Date + "' as Expiry_Date, '2' as QFix_Type, '0' as ss, '" + force_noon + "' as force_noon FROM epsc_ypca WHERE Pub_ID='" + Pub_ID + "' AND (Record_Ind='2' OR Record_Ind='4' OR Record_Ind='6');";
                   Statement insertQFDEL = conn1.createStatement();
                   insertQFDEL.execute(insertQfixDel);
              String updateRecords = "UPDATE epsc_ypca SET " + updateString + " WHERE Unique_ID='" + Unique_ID + "';";
         String selectAndInsert = "INSERT INTO epsc_quickfixes SELECT *, '0' as UID, '" + Start_Date + "' as Start_Date, '" + Expiry_Date + "' as Expiry_Date, '3' as QFix_Type, '" + ss + "' as ss, '" + force_noon + "' as force_noon FROM epsc_ypca WHERE Pub_ID='" + Pub_ID + "';";
         Statement insertIntoQfix = conn1.createStatement();
         insertIntoQfix.execute(selectAndInsert);
         out.write("Quickfix Successfully submitted.<BR><BR>\r\n");
    catch (SQLException e)
            out.write("<h1>SQL ERROR: " + e.getMessage() + "<BR><BR>Please report to administrator</h1>");
    finally{
            conn1.close();
    %>
    <BR><BR>[ <a href="menu.jsp">Return To Main</a> ]
    </center>
    </BODY>
    </HTML>
    <%
    %>

    it is the exact same as the one i originally posted:
    500 Servlet Exception
    java.lang.ClassCastException
         at quickfix0itm_0submit__jsp.addUpdate(/epsc/quickfix_itm_submit.jsp:24)
         at quickfix0itm_0submit__jsp._jspService(/epsc/quickfix_itm_submit.jsp:169)
         at com.caucho.jsp.JavaPage.service(JavaPage.java:75)
         at com.caucho.jsp.Page.subservice(Page.java:506)
         at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:182)
         at com.caucho.server.http.Invocation.service(Invocation.java:315)
         at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:135)
         at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:344)
         at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)
         at com.caucho.server.TcpConnection.run(TcpConnection.java:139)
         at java.lang.Thread.run(Thread.java:534)

  • Method declaration of an interface

    Hi,
    Here's an interface definition.
    public interface Foo {
    public Object getSomeObject(Object param);
    What i want to find out is,
    why do we need to specify a variable reference in the interface?
    public interface Foo {
    public Object getSomeObject(Object);//throws error.
    Thank you.

    Hi,
    Here's an interface definition.
    public interface Foo {
    public Object getSomeObject(Object param);
    What i want to find out is,
    why do we need to specify a variable reference inthe
    interface?
    public interface Foo {
    public Object getSomeObject(Object);//throwserror.
    Thank you.The interface method is just a signature that all
    classes implementing the interface must follow. Its
    syntax requires that the variable reference is
    included. There is no other reason. Its like the word
    "bought" is spelt the way it is..It could have also
    been splet as "bot" but that is incorrect.!!!
    That is right.
    It is just a signature. Also, it allows the compiler to perform its actions consistently, most of all, thereby not offering any special privileges to an interface method declaration. As we all know that the byte code representation of an 'interface type' is also a class.

  • Should I declare IllegalArgumentException in my method declaration

    Hi,
    I have a setter method which throws an IllegalArgumentException which is of type RuntimeException... It means that I need not declare it in my method declaration, but I should explicity describe in Javadoc.
    Is it a good practice to declare it in throws clause just to make it more readable? or is it superfluous and unnecessary because I am going to describe it in Javadoc anyway?
    I mean....
      * @throws IllegalArgumentException
    public void setterMethod() {
    vs
      * @throws IllegalArgumentException
    public void setterMethod() throws IllegalArgumentException {
    }Thank you,
    Srikanth

    I have a setter method which throws an
    IllegalArgumentException which is of type
    RuntimeException... It means that I need not declare
    it in my method declaration, but I should explicity
    describe in Javadoc.If you conclude that it is important that the other programmers know in which situation your method throws an IllegalArgumentException then go ahead and describe it in javadoc. If you think that it's not important, or it's not necessary, you don't need to describe it. But in general, the unchecked exception IllegalArgumentException, if it is used according to its purposes, deserves a javadoc description. Although I think you are not using this exception appropriately, because your method doesn't even have a parameter! I hope you are showing just an example, just to support your question.
    Is it a good practice to declare it in throws clause
    just to make it more readable? or is it superfluous
    and unnecessary because I am going to describe it in
    Javadoc anyway?No! It does not make it more readable. IllegalArgumentException is an unchecked exception, so you have to take advantage of this "uncheackability", that is, the advantage of not being needed to declare that the method throws it. In any case, you shouldn't declare the throws clause for any kind of unchecked exception. A description in javadoc is enough. But I see that you're just saying that the method can throw IllegalArgumentException, in the javadoc. Why don't you give more details? It is a good practice. See below an example:
      * @throws IllegalArgumentException if the parameter name passed is null,
      * or if it is equal to "".
    public void setterMethod(String name) {
    }

  • Method declaration problem

    Hi,
    I'm trying to write a class that lets the user enter the values for some parameters all of which are Floats.
    I have get and set methods for each parameter.
    example of some code:
    public class Parameters
           private Float loat affinityThresholdScalar;
            public InitialiseParams(Float aT)
                  affinityThresholdScalar = aT;
         public void setAffinityThresholdScalar(Float aT)
                  affinityThresholdScalar = aT;
           public Float getAffinityThresholdScalar()
                  return affinityThresholdScalar;
    }The error i'm getting is:
    invalid method declaration; return type required
    public InitialiseParams(Float aT,Float cR,Float hR,Float k,Float s,Float sV,Float tR)
    can anybody help?
    Thanks

    The error i'm getting is:
    invalid method declaration; return type required
    public InitialiseParams(Float aT,Float
    aT,Float cR,Float hR,Float k,Float s,Float sV,Float tR)
    can anybody help?Yup: read the error diagnostic: the compiler found a method 'InitialiseParams',
    but it didn't find the return type of that method (because you didn't supply any).
    Even methods that return nothing, return 'void', so you should simply
    alter the method definition to:public void InitialiseParams(Float aT) {
          affinityThresholdScalar = aT;
    }kind regards,
    Jos

  • Invalid method declaration; return type required

    The code:
              public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                timer.cancel(); //Terminate the timer thread
    public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
           new superball();
                    new Reminder(5);
            System.out.format("Task scheduled.%n");
    //= End of Testing =
        }Gives:
    "invalid method declaration; return type required"
    If i add void to public Reminder(int seconds) {It prints:
    cannot find symbol
    symbol : class Reminder
    location: class superball
    new Reminder(5);
    Is it because of the public class?
    public class superball extends JFrameHere is the FULL code:
    /*                      superball                                 */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.regex.Pattern;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.*;
    import java.io.*;
    * Summary description for superball
    public class superball extends JFrame
         // Variables declaration
         int ballx;
      int bally;
         int jumpstop;
         int stopper;
         int coin;
         int coinx;
         int coiny;
         int coinvaluex;
         int coinvaluey;
      Timer timer;
      private int value = 0;
         private static Random r = new Random();
         private JLabel jLabel1;
         private JLabel jLabel2;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel7;
         private JLabel jLabel9;
         private JLabel jLabel10;
         private JPanel contentPane;
         private JPanel jPanel1;
         // End of variables declaration
         public superball()
              super();
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              jLabel1 = new JLabel();
              jLabel2 = new JLabel();
              jLabel4 = new JLabel();
              jLabel5 = new JLabel();
              jLabel7 = new JLabel();
              jLabel9 = new JLabel();
              jLabel10 = new JLabel();
              coin = 1;
              coinx = Math.abs(r.nextInt()) % 460 + 100;
              coiny = Math.abs(r.nextInt()) % 200 + 100;
              ballx = 342;
              bally = 338;
              jumpstop = 0;
              stopper = 13;
              contentPane = (JPanel)this.getContentPane();
              jPanel1 = new JPanel();
              // jLabel1
              jLabel1.setIcon(new ImageIcon("IMG\\coin.gif"));
              jLabel1.setText("0");
              // jLabel2
              jLabel2.setIcon(new ImageIcon("IMG\\logo.PNG"));
              // jLabel4
              jLabel4.setIcon(new ImageIcon("IMG\\black.GIF"));
              // jLabel5
              jLabel5.setIcon(new ImageIcon("IMG\\ballstanding2.gif"));
              // jLabel7
              jLabel7.setIcon(new ImageIcon("IMG\\star-heart.gif"));
              jLabel7.setText(" 100");
              // jLabel9
              jLabel9.setIcon(new ImageIcon("IMG\\coin.gif"));
              // jLabel10
              jLabel10.setIcon(new ImageIcon("IMG\\stage1.GIF"));
              // contentPane
              contentPane.setLayout(null);
              contentPane.setBackground(new Color(255, 254, 254));
              addComponent(contentPane, jLabel5, 342,338,60,18);
              addComponent(contentPane, jLabel1, 561,4,100,18);
              addComponent(contentPane, jLabel2, 2,3,208,24);
              addComponent(contentPane, jLabel7, 495,4,60,18);
              addComponent(contentPane, jLabel9, coinx,coiny,19,18);
              addComponent(contentPane, jLabel2, 2,3,208,24);
              addComponent(contentPane, jLabel10, -2,29,738,412);
              addComponent(contentPane, jPanel1, 79,209,200,100);
              // jPanel1
              jPanel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
              jPanel1.setFocusable(true);
              jPanel1.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e)
                        jPanel1_keyPressed(e);
                   public void keyReleased(KeyEvent e)
                        jPanel1_keyReleased(e);
                   public void keyTyped(KeyEvent e)
                        jPanel1_keyTyped(e);
              // superball
              this.setTitle("Superball created by Hannes Karlsson");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(617, 450));
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jPanel1_keyPressed(KeyEvent e)
              System.out.println("\njPanel1_keyPressed(KeyEvent e) called.");
              // TODO: Add any handling code here
              if(e.getKeyCode()==e.VK_LEFT) // when the user enters left
                  jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                        } // equalling PLAIN_SPEED
                                            if(e.getKeyCode()==e.VK_RIGHT) // when the user enters right
                  jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                        } // equalling PLAIN_SPEED
                                                                if(e.getKeyCode()==e.VK_UP) // when the user enters up
                  jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setIcon(new ImageIcon("IMG\\balljetpack.gif"));
                        } // equalling PLAIN_SPEED
                                                                                    if(e.getKeyCode()==e.VK_DOWN) // when the user enters up
                  jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                        } // equalling PLAIN_SPEED     
                        if(bally>=340)
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                                  System.out.println("LOW!!!");
                        if(bally<=-2)
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                        jLabel5.setLocation(new Point(ballx, bally++));
                                  System.out.println("HIGH!!!");
                                            if(ballx>=594)
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                        jLabel5.setLocation(new Point(ballx--, bally));
                                  System.out.println("RIGHT!!!");
                                                                if(ballx<=-3)
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                        jLabel5.setLocation(new Point(ballx++, bally));
                                  System.out.println("LEFT!!!");
                                                                           if (bally==294 && (ballx > 218 && ballx < 274))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                                                                           if (bally==262 && (ballx > 246 && ballx < 306))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                                                       if (bally==230 && (ballx > 486 && ballx < 562))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                                        if (bally==310 && (ballx > 486 && ballx < 594))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                         if (bally==262 && (ballx > 442 && ballx < 514))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
          if (bally==294 && (ballx > 378 && ballx < 466))
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                        jLabel5.setLocation(new Point(ballx, bally--));
                   // COIN
                         if ((bally > coiny-10 && bally < coiny+10) && (ballx > coinx-10 && ballx < coinx+10))
                coinx = Math.abs(r.nextInt()) % 617 + 1;
                coiny = Math.abs(r.nextInt()) % 300 + 1;
                   jLabel9.setLocation(new Point(coinx, coiny));
                        System.out.println("Coinx:"+coinx+"");
                        System.out.println("Coiny:"+coiny+"");
                        jLabel1.setText(""+ coin++ +"");
                        System.out.println("Ballx:"+ballx+"");
                        System.out.println("Bally:"+bally+"");
         private void jPanel1_keyReleased(KeyEvent e)
              System.out.println("\njPanel1_keyReleased(KeyEvent e) called.");
              // TODO: Add any handling code here
              jLabel5.setIcon(new ImageIcon("IMG\\ballstanding2.gif"));
         private void jPanel1_keyTyped(KeyEvent e)
              System.out.println("\njPanel1_keyTyped(KeyEvent e) called.");
              // TODO: Add any handling code here
         // TODO: Add any method code to meet your needs in the following area
    //============================= Testing ================================//
    //=                                                                    =//
    //= The following main method is just for testing this class you built.=//
    //= After testing,you may simply delete it.                            =//
    //======================================================================//
              public void Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                timer.cancel(); //Terminate the timer thread
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
           new superball();
                    new Reminder(5);
            System.out.format("Task scheduled.%n");
    //= End of Testing =
    }

    No, it's because you can't have a constructor called Reminder if you don't have a class named Reminder.

  • Invalid method declarations?

    hi, new to JAVA, and i have a problem, I am getting invalid method declarations for "printStraightLine()" and "printSumOfYears();" and would like them to become valid so that way i am able to start cracking away at the formulas...any type of suggestions would be appreciated...Mike...so here's the code:
    import java.io.*;
      class Depreciation
        private char choice;
        private int purchasePrice;
        private int salvageValue;
        private int usefulLife;
        private printSumOfYears();
        private printStraightLine();
        private double deprec;
       Depreciation()   {}
       Depreciation(char choice, int purchasePrice, int salvageValue, int usefulLife)
           this.choice = choice;
           this.purchasePrice = purchasePrice;
           this.salvageValue = salvageValue;
           this.usefulLife = usefulLife;
        public char getchoice()
                {return choice;}
        public int getpurchasePrice()
                {return purchasePrice;}
        public int getsalvageValue()
                {return salvageValue;}
        public int getusefulLife()
                {return usefulLife ;}
      void setDepreciation(int purchasePrice, int salvageValue, int usefulLife)
        this.purchasePrice = purchasePrice;
          this.salvageValue = salvageValue;
          this.usefulLife = usefulLife;
      void setChoice(char choice)
      {  this.choice = choice;}
    public printStraightLine()
    {   double deprec;
        while (usefulLife < 0);
        for (usefulLife = 1; usefulLife <= usefulLife; usefulLife++)
            deprec = (purchasePrice - salvageValue) / (usefulLife);
            System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public printSumOfYears()
      { double deprec;
          while (usefulLife <=1);
          for (usefulLife = usefulLife; usefulLife <= 1; usefulLife--)
              deprec =
              System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String toString();
              String s = new String();
              s = ' ' + "Purchase Price = " + purchasePrice + "  " + "Salvage Value = " + salvageValue + "  " + "Use Life = " + usefulLife + "  " + "Sum of Years = " + SumOfYears + "  " + "Straight Line = " + StraightLine;
              return s;
     

    That did it! I forgot to declare printSumof... and print Straight... as String Methods...
    ok now ive gotten rid of all the syntax errors in it and now ive run into a larger problem...the menu class that i have, wont accept my Depreciation...i think its perhaps theres something wrong with the toString Method perhaps but this is the last bit i need to get over the hill, per se...so heres the Depreciation Coding(without syntax errors and following it will be my MenuDrivenClass that corresponds....
    DEPRECIATION CODING
    import java.io.*;
      class Depreciation
        private char choice;
        private double purchasePrice;
        private double salvageValue;
        private int usefulLife;
       Depreciation()   {}
       Depreciation(char choice, double purchasePrice, double salvageValue, int usefulLife)
           this.choice = choice;
           this.purchasePrice = purchasePrice;
           this.salvageValue = salvageValue;
           this.usefulLife = usefulLife;
        public char getChoice()
                {return choice;}
        public double getpurchasePrice()
                {return purchasePrice;}
        public double getsalvageValue()
                {return salvageValue;}
        public int getusefulLife()
                {return usefulLife ;}
      void setDepreciation(double purchasePrice, double salvageValue, int usefulLife)
        this.purchasePrice = purchasePrice;
          this.salvageValue = salvageValue;
          this.usefulLife = usefulLife;
      void setChoice(char choice)
      {  this.choice = choice;}
    public String printStraightLine()
    {   double deprec;
        while (usefulLife < 0);
        for (usefulLife = 1; usefulLife <= usefulLife; usefulLife++)
            deprec = (purchasePrice - salvageValue) / (usefulLife);
            System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String printSumOfYears() //musthave decrementing loop
      { double deprec;
          while (usefulLife >=1);
          for (usefulLife = usefulLife; usefulLife >= 1; usefulLife--)
              deprec = 20-10;
              System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String toString()
              String d = new String();
              d = ' ' + "Purchase Price = " + purchasePrice + "  " + "Salvage Value = " + salvageValue + "  " + "Use Life = " + usefulLife + "  " + "Sum of Years = " + printSumOfYears() + "  " + "Straight Line = " + printStraightLine();
              return d;
      NOW HERES THE MENU DRIVEN CLASS
    // Professor Dreher
    import java.text.DecimalFormat;
    import java.io.*;
    public class MenuDrivenClass2
        public static void main(String[] args)throws IOException
          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
          char choice;
          Depreciation myDepreciation = new Depreciation();
          do
            PrintMenu();
            choice = GetChoice();
            switch (choice)
              case 'i': myDepreciation= getInput();
                        break;
              case 'a': System.out.println(myDepreciation);
                        myDepreciation.printStraightLine();
                        break;
              case 'b': System.out.println(myDepreciation);
                        myDepreciation.printSumOfYears();
                        break;
              case 'q': System.out.print(" Goodbye, have a nice day! ");
                        break;
           }//ends switch
         }while(choice != 'q');
       }//ends main
      static void PrintMenu()
          System.out.println("\n\n i - to input new depreciation information ");
          System.out.println(" a - to use the straight-line method ");
          System.out.println(" b - to use the sum-of-the-years' digits method ");
          System.out.println(" q - to quit ");
          System.out.print(" --> " );
      static char GetChoice()throws IOException
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           char choice;
           do
             String text = in.readLine();
             choice = Character.toLowerCase(text.charAt(0));
             if(choice != 'i' && choice != 'a' && choice != 'b'  && choice != 'q')
               {  System.out.print(" Incorrect choice, please try again! ");}
            } while (choice != 'i' && choice != 'a' && choice != 'b'  && choice != 'q');
           return(choice);
      static Depreciation getInput()throws IOException
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           System.out.print("\n Enter Purchase Price: ");
           double purchasePrice = Double.parseDouble(in.readLine());
           System.out.print(" Enter Salvage Value: ");
           double salvageValue = Double.parseDouble(in.readLine());
           System.out.print(" Enter Useful Life: ");
           int usefulLife = Integer.parseInt(in.readLine());
           Depreciation d = new Depreciation(purchasePrice,salvageValue,usefulLife);
           return(d);              
    }IN THE LAST LINE(Depreciation d=....), the "new" is a syntax error, reading..."cannot resolve symbol Depreciation (double, double, int) @ line 86"....I thank all for helping me...the Duke Dollars is now up to 10...any help is greatly appreciated....SO, any thoughts?

  • Strange about invoking web service method declared “string  method(void)”;

    Dear forum readers
    I’m experimenting with OpenESB and web services. I’ve create a simple web service using NetBeans 6.1. The method consists of a single method, getTime, that is declared:
    String getTime()
    My current experiment is to invoke this method from a BPEL-process using the “Invoke” process object. The strange thing is that it seems like I have to provide a “dummy” inbound variable from the BPEL-designer even though the method doesn’t take any parameters. I include a snippet from the BPEL process below which includes the section where I set the dummy GetTimeIn-variable and then invokes the WS method getTime().
    <assign name="Assign2">
    <copy>
    <from>'DummyValue'</from>
    <to variable="GetTimeIn" part="parameters"/>
    </copy>
    </assign>
    <invoke name="Invoke1" partnerLink="PartnerLink1" operation="getTime" xmlns:tns="http://ws/" portType="tns:MyWebService" outputVariable="GetTimeOut" inputVariable="GetTimeIn"/>
    If I don’t initiate the dummy variable or remove it altogether, I can’t successfully call the method. If I include the dummy in-parameter the call works just fine and I get back the current time as a string.
    I must admit that I’m still a rookie to web services, especially when calling them from a BPEL-process, so it may be a very trivial reason for this behaviour. Anyway, any help on this matter would be greatly appreciated.
    Regards, Ola

    Thank you both for the response. Regarding Rennay’s posting I have an additional question. When I create a new web service I don't have the "Document Literal" option nor a "Concrete Configuration" tab. I've created the web service using the "Web Application" project type and then adding a web service using the "Web Service..." wizard. This wizard doesn't have the configuration properties you mention, but if I add a WSDL-file to a BPEL-project the wizard has the properties you mention.
    Is it possible to create a web service, programmed as an ordinary Java-class, from an existing WSDL-file? In that case it may solve the problem with the “Document Literal” property. Currently I don’t know any other way to create such a web-service other than the through the web service wizard in a web application project. Of course, it’s possible to craft it from scratch but that’s to much work to be practical.
    Regards, Ola

  • Java.lang.NullPointerException in checkTransaction method

    EJB2.1 / weblogic 10.3
    I get en nullpointerexception in a weblogic generated class.
    The method in the generated class is :
    private void checkTransaction()
    weblogic.transaction.Transaction tx = (weblogic.transaction.Transaction)
    TransactionHelper.getTransactionHelper().getTransaction();
    if ((tx == null) && (__WL_createTxId == null))
    return;
    else if ((tx == null) && (__WL_createTxId != null))
    if (! true) {
    Loggable l1 = EJBLogger.logaccessedCmrCollectionInDifferentTransactionLoggable("CustomOffice", "officehours");
    throw new IllegalStateException(l1.getMessage());
    else if (!tx.getXid().equals(__WL_createTxId) && ! true ) {
    Loggable l1 = EJBLogger.logaccessedCmrCollectionInDifferentTransactionLoggable("CustomOffice", "officehours");
    throw new IllegalStateException(l1.getMessage());
    I get the nullpointer at the line
    else if (!tx.getXid().equals(__WL_createTxId) && ! true ) {
    I have an EntityBean named CustomOffice, this bean has a collection of Officehours entitybeans.
    When I call ( from a SessionBean with @ejb.transaction type="Supports" )
    Iterator iter = customOfficeLocal.getOfficehours().iterator();
    I get the NullPointeException when not using an transaction, when using a transaction it works.
    But I would llike to call this witout an transaction.

    The method checkTransaction is in a weblogic generated class.
    java.lang.NullPointerException
         at dk.steria.exp.midtier.model.customs.ejb.CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.checkTransaction(CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.java:644)
         at dk.steria.exp.midtier.model.customs.ejb.CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.iterator(CustomOffice_up2n56__WebLogic_CMP_RDBMS_officehours_Set.java:186)
         at dk.steria.exp.midtier.tools.factory.DeclarationFactory.createOfficeHoursTOList(DeclarationFactory.java:1443)
         at dk.steria.exp.midtier.tools.factory.DeclarationFactory.createCustomOfficeTO(DeclarationFactory.java:1415)
    The error comes when I call
    Iterator iter = customOfficeLocal.getOfficehours().iterator();
    in my code.
    I guess it is because I am using a EJB 2.1 entitybean.... that needs a transaction ??????

  • Invalid method declaration

    Hi there,
    I have a problem to compile below sentences.
    import java.awt.* ;
    import javax.swing.* ;
    import java.awt.event.* ;
    public class p662 extends JFrame
    public ShowColors()
    ** invalid method declariration for ShowColors ****
    super ("Using colors") ;
    Please help me.
    Best regards

    What the diddley?
    Your class name is p662 (what the heck is that?).
    The declaration public ShowColors looks like a constructor. You call super in it with a String argument, which looks like you want to invoke a JFrame ctor.
    You can't invoke a super class constructor in any method except a class constructor. The class constructors must have the same name as the class. The class must go in a file whose name is the same as the public class inside.
    You should follow the Sun coding standards for naming:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
    What are you doing here? This is unintelligible. - MOD

  • SAX XML NullPointerException in character() method

    I'm having issues when parsing my xml file. Everything works fine unless I am trying to push values into my parameters Vector.
    class SAXLoader extends DefaultHandler {
        private static String className, //name of the class for module in xml
                methodName,              //name of the method for the class
                path;                    //path to jar. should be in URI format
        private Vector params;      //parameters to the method
        private boolean isClassName,     //true if element begins className tag
                isMethodName,            //true if element begins methodName tag
                isParameter,             //true if element begins parameter tag
                isPath;                  //true if element begins path tag
        //=======================init()================================
        //opens XML file specified and parses it for className,
        //the methodName,and the path to the JAR
        //This should be called before doing any of the getter methods
        //=============================================================
        public void init() {
            try {
                XMLReader xmlreader = XMLReaderFactory.createXMLReader();
                SAXLoader handler = new SAXLoader();
                xmlreader.setContentHandler(handler);
                xmlreader.setErrorHandler(handler);
                try {
                    FileReader r = new FileReader("myclass.xml");
                    xmlreader.parse(new InputSource(r));
                } catch (FileNotFoundException e) {
                    System.out.println("File Not Found!");
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    System.out.println("Parse Error!");
                    e.printStackTrace();
            } catch (Exception e) {
                System.out.println("XML Reader Error!");
                e.printStackTrace();
    public void characters(char ch[], int start, int length) {
            String temp = "";
            for (int i = start; i < start + length; i++) {
                switch (ch) {
    case '\\':
    // System.out.print("\\\\");
    break;
    case '"':
    // System.out.print("\\\"");
    break;
    case '\n':
    // System.out.print("\\n");
    break;
    case '\r':
    // System.out.print("\\r");
    break;
    case '\t':
    // System.out.print("\\t");
    break;
    default:
    temp += ch[i];
    break;
    if (isClassName) {
    className = temp;
    } else if (isMethodName) {
    methodName = temp;
    } else if (isPath) {
    path = temp;
    } else if (isParameter) {
    System.out.println("zomg!: " + temp);
    params.add(temp);
    } //end of characters(...
    Right there at params.add(temp);
    I'm using this DefaultHandler based class to parse an XML file for information regarding a user's own class [its classname, its methodname, and the methods parameters].
    Any clues?
    Message was edited by:
    nick.mancuso
    Message was edited by:
    nick.mancuso

    You don't actually allocate the params Vector, at least not on the code you've posted. You want something like:
    private Vector params = new Vector();or better yet:
    private List params = new LinkedList();perhaps.
    But even better yet...I suspect that having a handful of global temp variables like that isn't going to work. In my experience, when using SAX you pretty much have to create a stack to hold the current place in the XML tree. That's how you traverse trees, with stacks. Then instead of setting isMethodName, isParameter, etc. (which I presume you do in open/close tag handlers) you define an enumeration of values like "class", "method", "parameter", and then have a stack of those values, or something.

  • NullPointerException on String methods

    All,
    I am trying to get date values on the fly and add them to my sql statement. I have a DateWorker class that provides month, day of month and year.
    When I use the class in another class, I get NullPointerException. These are just plain ol' String methods, why are they giving me problems. When I run the code on its won, it works fine.
    Code:
    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
    public DateWorker dateWorker;
         public DateWorker(){
              dateWorker = new DateWorker()
         public static void main(String[] args){
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         private Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
    Edited by: ink86 on Oct 8, 2007 12:57 PM

    package mybeans;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.util.HashMap;
    import java.util.Calendar;
    public class DateWorker {
         public static void main(String[] args){
              DateWorker dateWorker = new DateWorker();
              String m = dateWorker.getMonth();
              String dm = dateWorker.getDayOfMonth();
              String dw = dateWorker.getDayOfWeek();
              String y = dateWorker.getYear();
              System.out.println("day of week " + dw + "<BR>");
              System.out.println("day of month" + dm + "<BR>");
              System.out.println("month " + m + "<BR>");
              System.out.println("year " + y + "<BR>");
         //get a Calendar instance.
         Calendar cal = Calendar.getInstance();
         //gets the current month
         public String getMonth(){
         int x = cal.get(Calendar.MONTH) + 1;
         String s = String.valueOf(x);
         return s;
         //gets the current day of month
         public String getDayOfMonth(){
              int x = cal.get(Calendar.DAY_OF_MONTH);
              String s = String.valueOf(x);
              return s;
         //gets the current day of week
         public String getDayOfWeek(){
              int x = cal.get(Calendar.DAY_OF_WEEK) -1;
              String s = String.valueOf(x);
              return s;
         //gets the current year
         public String getYear(){
              int x = cal.get(Calendar.YEAR);
              String s = String.valueOf(x);
              return s;
         }

  • NullPointerException on object methods

    Hello everybody! I just started learning Java yesterday, and am looking forward to contributing to the forum!
    Here is a code I was working on today- it's the start of a simple game of blackjack.
    import java.util.Scanner;
    class BlackJack {
         public static void main(String[] args) {
              Deck deck = new Deck();
              System.out.print("Enter your name > ");
              Scanner in = new Scanner(System.in);
              String name = in.nextLine();
              Hand phand = new Hand(name);
              phand.addCards(2,deck);
              Hand dhand = new Hand("Dealer");
              dhand.addCards(2,deck);
              System.out.println("Dealer: "+dhand.readHand(true));
              System.out.println("You:    "+phand.readHand());
              System.out.println(phand.sum);
    }Then here is the Deck class:
    import java.util.Random;
    public class Deck {
         private int[] cards;
         public int getCard() {
              Random generator=new Random();
              int randomInt, out;
              do {randomInt=generator.nextInt(52);}
              while (cards[randomInt]==0);
              out=cards[randomInt];
              cards[randomInt]=0;
              return out;
         public void shuffle() {
              int[] newCards={1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
              cards=newCards;
         public Deck() {
              int[] cards = {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
    }And here is the Hand class:
    public class Hand {
         private int[] cards;
         private int sum;
         public String name;
         public void addCards(int numCards, Deck deck) {
              for (int i=0;i<numCards;i++) {
                   int newCard=deck.getCard();
                   cards[cards.length]=newCard;
                   sum+=newCard;
         public int getSum() {
              return sum;
         public String readHand(boolean isHidden) {
              String out="";
              if (isHidden) {
                   out=cards[0]+" x";
              else {
                   for (int i=0;i<cards.length;i++) {
                        out+=cards[i]+" ";
              return out;
         public String readHand() {
              return readHand(false);
         public Hand(String newName) {
              cards=new int[10];
              sum=0;
              name=newName;
    }Now I'm getting this runtime error:
    Exception in thread "main" java.lang.NullPointerException
            at Deck.getCard(Deck.java:8)
            at Hand.addCards(Hand.java:7)
            at BlackJack.main(BlackJack.java:9)I found online that the NullPointerException means that the object I'm calling is null, but I can't figure out why. I assume it's a simple thing that I overlooked (or haven't learned yet), but the curious thing is when I commented out the lines which caused the exception, and made the sum from the hand class public, I could use it fine. Any help is greatly appreciated!
    -seveneightn9ne

    Now compiling Deck results in these errors:
    Deck.java:7: cannot find symbol
    symbol  : variable cards
    location: class Deck
            cards = new int[] {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,
    10,10,10,10,10,10,10,10,10,10,10,10,10};
            ^
    Deck.java:13: cannot find symbol
    symbol  : variable cards
    location: class Deck
                    while (cards[randomInt]==0);
                           ^
    Deck.java:14: cannot find symbol
    symbol  : variable cards
    location: class Deck
                    out=cards[randomInt];
                        ^
    Deck.java:15: cannot find symbol
    symbol  : variable cards
    location: class Deck
                    cards[randomInt]=0;
                    ^
    Deck.java:20: cannot find symbol
    symbol  : variable cards
    location: class Deck
                    cards=newCards;
                    ^
    5 errorsHere is what Deck currently looks like:
    import java.util.Random;
    public class Deck {
         public Deck() {
         cards = new int[] {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
         public int getCard() {
              Random generator=new Random();
              int randomInt, out;
              do {randomInt=generator.nextInt(52);}
              while (cards[randomInt]==0);
              out=cards[randomInt];
              cards[randomInt]=0;
              return out;
         public void shuffle() {
              int[] newCards={1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
              cards=newCards;
    }Is it correct that cards is not declared outside the constructor, or is that the cause of the error?

  • Method declaration

    Why this method signature is valid?
    double method()[]

    Artefact from C => C++ => Java.
    C++ has to allow the C-style arrays because it has to compatible with
    C... but why this was also carried over to Java is a mystery to me.To keep the C/C++ programmers happy? When I started studying Java
    some ten years ago I had to get used to that "String[] args" thingy.
    Everytime it popped up I was thinking what's that identifier doing there
    at the end?" ;-)
    I still remember old pre-ANSI/C where the 'typedef' hack was just been
    introduced in the late seventies. You could write down almost any
    combination of declarator syntax stuff and the compiler would still be
    happy, e.g.int typedef * i;was perfectly valid in those days and the semantic analyzer would simply
    go: yeah, right: 'i' is an identifier but the parser saw a 'typedef' somewhere
    so 'i' will synonymous with the type of 'i' which won't be a variable identifier
    anymore ;-)
    Those were the days when vaxen ruled the world and every pointer was
    a machine word which was an integer ;-)
    kind regards,
    Jos (<--- old sod)

  • NullPointerException in Remote method

    Hello,
    I am trying to reproduce the database sample of the Java Roadmap using EJB's. I have gone through all the steps, deploying went well, compiling too. but when running the selectEJB Client program I get the following messages:
    "C:\Program Files\Oracle\JDeveloper 3.1\java\bin\javaw.exe" -mx50m -classpath "U:\Documentation\EJB;C:\Program Files\Oracle\JDeveloper 3.1\lib\jdev-rt.zip;C:\Program Files\Oracle\JDeveloper 3.1\jdbc\lib\oracle8.1.6\classes111.zip;C:\Program Files\Oracle\JDeveloper 3.1\lib\connectionmanager.zip;C:\Program Files\Oracle\JDeveloper 3.1\lib\javax_ejb.zip;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\aurora_client.jar;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\vbjorb.jar;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\vbjapp.jar;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\vbjtools.jar;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\vbj30ssl.jar;C:\Program Files\Oracle\JDeveloper 3.1\aurora\lib\aurora.zip;C:\Program Files\Oracle\JDeveloper 3.1\sqlj\lib\translator.zip;U:\Documentation\EJB\selectEJBRemoteSource.jar;U:\Documentation\EJB\selectEJBRemoteGenerated.jar;C:\Program Files\Oracle\JDeveloper 3.1\java\lib\classes.zip" selectO8iClient.MyEJBClient
    Creating an initial context
    Looking for the EJB published as 'test/selectEJBRemote'
    Creating a new EJB instance
    Caught RuntimeException in remote method; nested exception is:
    java.lang.NullPointerException:null
    Remote Stack Trace:
    java.lang.NullPointerException
    at selectEJB.selectEJBClass.ejbCreate(selectEJBClass.java:41)
    at oracle.aurora.ejb.gen.test_selectEJBRemote.EjbHome_selectEJBHome.create(EjbHome_selectEJBHome:52)
    at selectEJB._tie_selectEJBHome.create(_tie_selectEJBHome.java:53)
    at selectEJB._selectEJBHomeImplBase._execute(_selectEJBHomeImplBase.java:65)
    at selectEJB._selectEJBHomeImplBase._execute(_selectEJBHomeImplBase.java:53)
    at com.visigenic.vbroker.orb.SkeletonDelegateImpl.execute(SkeletonDelegateImpl.java:129)
    at oracle.aurora.server.GiopProtocolAdapter.doRequest(GiopProtocolAdapter.java:266)
    at com.visigenic.vbroker.orb.GiopProtocolAdapter.dispatchMessage(GiopProtocolAdapter.java:462)
    at oracle.aurora.server.ThreadSessionDispatcher.run(ThreadSessionDispatcher.java:92)
    at oracle.aurora.server.VCIiopConnection.processRequest(VCIiopConnection.java:62)
    at oracle.aurora.server.GiopServer._service(GiopServer.java:82)
    at oracle.aurora.server.GiopServer.service(GiopServer.java:191)
    at oracle.aurora.net.VirtualCircuit.processRequest(VirtualCircuit.java:201)
    at oracle.aurora.net.Presentation.handleRequest(Presentation.java:292)
    oracle.aurora.ejb.RemoteRuntimeException: Caught RuntimeException in remote method; nested exception is:
    java.lang.NullPointerException:null
    Remote Stack Trace:
    java.lang.NullPointerException
    at selectEJB.selectEJBClass.ejbCreate(selectEJBClass.java:41)
    at oracle.aurora.ejb.gen.test_selectEJBRemote.EjbHome_selectEJBHome.create(EjbHome_selectEJBHome:52)
    at selectEJB._tie_selectEJBHome.create(_tie_selectEJBHome.java:53)
    at selectEJB._selectEJBHomeImplBase._execute(_selectEJBHomeImplBase.java:65)
    at selectEJB._selectEJBHomeImplBase._execute(_selectEJBHomeImplBase.java:53)
    at com.visigenic.vbroker.orb.SkeletonDelegateImpl.execute(SkeletonDelegateImpl.java:129)
    at oracle.aurora.server.GiopProtocolAdapter.doRequest(GiopProtocolAdapter.java:266)
    at com.visigenic.vbroker.orb.GiopProtocolAdapter.dispatchMessage(GiopProtocolAdapter.java:462)
    at oracle.aurora.server.ThreadSessionDispatcher.run(ThreadSessionDispatcher.java:92)
    at oracle.aurora.server.VCIiopConnection.processRequest(VCIiopConnection.java:62)
    at oracle.aurora.server.GiopServer._service(GiopServer.java:82)
    at oracle.aurora.server.GiopServer.service(GiopServer.java:191)
    at oracle.aurora.net.VirtualCircuit.processRequest(VirtualCircuit.java:201)
    at oracle.aurora.net.Presentation.handleRequest(Presentation.java:292)
    at selectEJB._st_selectEJBHome.create(_st_selectEJBHome.java:68)
    at selectO8iClient.MyEJBClient.main(MyEJBClient.java:110)
    End...java.io.IOException: read error
    I have tried debugging the code and there seems to be a problem with creating the remoteInterface:
    selectEJBRemote remoteInterface = homeInterface.create();
    I just can't figure out what. Can someone help me?
    Thanks,
    Benny

    I have encountered exactly the same problem when creating a BMP Entity Bean. Has someone found a solution yet ?

Maybe you are looking for

  • Randomly monitor small office network

    Looking for a user-friendly, dummy-proof article on creating a small office network from a total of four Mac's (3 iMacs, one Air), allowing the administrator to randomly monitor without detection the real-time activities taking place on the other two

  • Unable to Enforce Unique Values, Duplicate Values Exist

    I have list in SP 2010, it contains roughly 1000 items.  I would like to enforce unique values on the title field.  I started by cleaning up the list, ensuring that all items already had a unique value.  To help with this, I used the export to excel

  • Binding for table produces list for other tables using foreign key and crea

    Using software Jdev 11G, WLS 11G, Oracle DB 11G, Windows Vista platform technology EJB 3.0, jspx, backing beans, session bean I cannot create a namedquery on my secondary table. The method for the column uses the entity object rather than the name an

  • I forgot my security question answers and my backup email isn't mine, how do I fix it?

    I was trying to buy something off of the itunes store, they asked for my security question and I forgot the answers. Went to apple ID settings and tried to change the questions but I couldn't. They have a rescue email for me but it's not mine..How ca

  • Finding proper help on Hierarchical Trees

    Have spent a couple of hours trying to navigate the sprawling website of oracle.com with the purpose finding and then downloading the appropriate help file. I downloaded Oracle9i Developer Suite Release 2 Documentation Library from http://www.oracle.