HELP!!!  NumberFormatException!!!

Can you find anything wrong this code that causes a NumberFormatException? I'm a beginner, so I haven't got to exception handling yet. I'm working from Deitel and Deitel's book "Java 2: How to Program". I don't care what number I put in (with or without a decimal point), the exception is always there. I don't see anything wrong with the code. Do you? Please feel free to copy this code and use it on your own computer, and let me know what works for you. Your help will be greatly appreciated. Here I've posted the code and below it is the runtime error message.
// Exercise 12.13
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Temperature extends JFrame
private JLabel enterTemp, convertTemp;
private JTextField tempField, resultsField;
private JComboBox scales;
private JRadioButton scaleButtons[];
private ButtonGroup rbGroup;
private JPanel top, middle, bottom;
private Container c;
private String scaleNames[] = {"Fahrenheit", "Centigrade", "Kelvin"};
private RadioButtonHandler handler;
public Temperature()
super("Temperature Conversion App");
c = getContentPane();
c.setLayout(new GridLayout(3,1));
setupTop();
setupMiddle();
setupBottom();
setSize(500,300);
show();
public void setupTop()
top = new JPanel();
top.setLayout(new FlowLayout());
enterTemp = new JLabel("Please enter a temperature:");
top.add(enterTemp);
tempField = new JTextField(5);
top.add(tempField);
scales = new JComboBox(scaleNames);
scales.setMaximumRowCount(1);
top.add(scales);
c.add(top);
public void setupMiddle()
middle = new JPanel();
middle.setLayout(new FlowLayout());
convertTemp = new JLabel("I wanna convert this to:");
middle.add(convertTemp);
handler = new RadioButtonHandler();
scaleButtons = new JRadioButton[3];
rbGroup = new ButtonGroup();
for (int i=0; i < scaleButtons.length; i++)
scaleButtons[i] = new JRadioButton(scaleNames, false);
scaleButtons[i].addItemListener(handler);
rbGroup.add(scaleButtons[i]);
middle.add(scaleButtons[i]);
c.add(middle);
public void setupBottom()
bottom = new JPanel();
bottom.setLayout(new FlowLayout());
resultsField = new JTextField(50);
resultsField.setEditable(false);
bottom.add(resultsField);
c.add(bottom);
private class RadioButtonHandler implements ItemListener
public void itemStateChanged(ItemEvent e)
if (e.getSource()==scaleButtons[0])
     if (scales.getSelectedIndex()==0)
     resultsField.setText("You already have the Fahrenheit temp!");
     else if (scales.getSelectedIndex()==1)
convertF2C(enterTemp.getText());
     else if (scales.getSelectedIndex()==2)
     convertF2K(enterTemp.getText());
} // end if
if (e.getSource()==scaleButtons[1])
     if (scales.getSelectedIndex()==0)
     convertC2F(enterTemp.getText());
     else if (scales.getSelectedIndex()==1)
     resultsField.setText("You already have the Centigrade temp!");
     else if (scales.getSelectedIndex()==2)
     convertC2K(enterTemp.getText());
} // end if
if (e.getSource()==scaleButtons[2])
     if (scales.getSelectedIndex()==0)
     convertK2F(enterTemp.getText());
     else if (scales.getSelectedIndex()==1)
     convertK2C(enterTemp.getText());
     else if (scales.getSelectedIndex()==2)
     resultsField.setText("You already have the Kelvin temp!");
} // end itemStateChanged
} // end RadioButtonHandler
public void convertF2C(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Fahrenheit is "+((5/9)*(temp-32)) + " degrees
Centigrade.");
public void convertF2K(String input)
{ double temp = 0.0;
temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Fahrenheit is "+((5/9)*(temp-32)+273) + " degrees
Kelvin.");
public void convertC2F(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Centigrade is " +((9/5)*temp+32) + " degrees
Fahrenheit.");
public void convertC2K(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Centigrade is " +(temp+273) + " degrees Kelvin.");
public void convertK2F(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Kelvin is " +((9/5)*(temp-273)+32) + " degrees
Fahrenheit.");
public void convertK2C(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Kelvin is " + (temp-273) + " degrees Centigrade.");
public static void main(String args[])
Temperature app = new Temperature();
app.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
     System.exit(0);
} // end main
} // end class
C:\jdk1.2.1\bin>java Temperature
Exception occurred during event dispatching:
java.lang.NumberFormatException: Please enter a temperature:
at java.lang.FloatingDecimal.readJavaFormatString(Compiled Code)
at java.lang.Double.parseDouble(Double.java:188)
at Temperature.convertC2F(Temperature.java:129)
at Temperature$RadioButtonHandler.itemStateChanged(Temperature.java:95)
at javax.swing.AbstractButton.fireItemStateChanged(Compiled Code)
at javax.swing.AbstractButton$ForwardItemEvents.itemStateChanged(Abstrac
tButton.java:1112)
at javax.swing.DefaultButtonModel.fireItemStateChanged(Compiled Code)
at javax.swing.JToggleButton$ToggleButtonModel.setSelected(JToggleButton
.java:222)
at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.
java:239)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
istener.java:217)
at java.awt.Component.processMouseEvent(Component.java:3126)
at java.awt.Component.processEvent(Compiled Code)
at java.awt.Container.processEvent(Compiled Code)
at java.awt.Component.dispatchEventImpl(Compiled Code)
at java.awt.Container.dispatchEventImpl(Compiled Code)
at java.awt.Component.dispatchEvent(Compiled Code)
at java.awt.LightweightDispatcher.retargetMouseEvent(Compiled Code)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:1732)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:1645)
at java.awt.Container.dispatchEventImpl(Compiled Code)
at java.awt.Window.dispatchEventImpl(Window.java:714)
at java.awt.Component.dispatchEvent(Compiled Code)
at java.awt.EventQueue.dispatchEvent(Compiled Code)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:68)

Of course you can also just stick your code in a try... catch block and handle the exceptions as they arise. This would probably be sub-optimal if you were getting a lot of them though.
Of course you could combine both and create a helper method to parse your double values.
public double getDoubleValueFromString(String input) {
  double myDouble = 0;
  try {
    if(!isEmptyOrNull(input)) {
      myDouble =  Double.parseDouble(input);
  catch (NumberFormatException ex) {
    // Handle this exception how ever you want.
  finally {
    // This is to annoy a certain somebody in the forums
    return myDouble;

Similar Messages

  • "Exception in thread "main" java.lang.NumberFormatException"error..pls help

    Hi,
    I'm trying to run a program I've written but keeping getting this error:
    Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:994)
    at java.lang.Double.parseDouble(Double.java:482)
    at data.newLineToRead(data.java:21)
    at data.data(data.java:34)
    at train.main(train.java:86)
    I'm not quite sure where I'm going wrong.I've included the data class and train class.Could someone pls help me.
    Thanks a lot.
    Data Class:
    import java.io.*;
    import java.util.*;
    public class data{
            private static parameter par;
            private static double[][] x=new double[par.n()][par.D()];
            public static double[] t=new double[par.n()];
            public static void newLineToRead(String LineToRead,int n){
            int d=0;
            String stringToRead=new String();
                    for(int i=0;i<=LineToRead.length();i++){
                            StringTokenizer str = new StringTokenizer (stringToRead,"/t");
                            String[] strtemp = new String[str.countTokens()];
                                    while (str.hasMoreTokens()){
                                    x[n][d++] = Double.parseDouble(str.nextToken());
                                    d++;
                                    System.out.println(x[n][d++]);
                            stringToRead=new String();
                    t[n]=Double.parseDouble(stringToRead);
                    x[n][par.d()]=1.0;
            public static void data() throws IOException{
            DataInputStream in=null;
                    try{
                            in=new DataInputStream(new FileInputStream(par.f()));
                            for(int n=0;n<par.n();n++){
                            String LineToRead=in.readLine();
                                    if(LineToRead.length()==0){
                                            System.out.println("Remove empty lines");
                                    else{
                                            newLineToRead(LineToRead,n);
                    }finally{if(in!=null){in.close();}}
            public static double x(int n,int d){return x[n][d];}
            public static double t(int n){return t[n];}
    }Train Class
    import java.io.*;
    import java.util.*;
    public class train{
             private static parameter       par;
             private static data            dat;
             private static model           mod;
             private static response        resp;
             private static void error(String msg){
                    System.out.println(msg);
                    System.exit(1);
             private static void check(){
                if(par.f().length()==0)
                    error("No filename of input vectors!");
                if(par.n()==0)
                    error("No number of input vectors!");
                if(par.d()==0)
                    error("No number of input variables!");
                if(par.d()>par.D())
                    error("Dimension is larger than 100!");
              private static void usage(){
                System.out.println("Non-default parameters==========================");
                System.out.println("-f filename of input vectors");
                System.out.println("-n number of input vectors");
                System.out.println("-d number of input variables");
                System.out.println("Default parameters==========================");
                System.out.println("-R regularisation constant (must be positive and the default value is 0.0)");
                System.out.println("-S epsilon criterion for stopping a learning process (default value is 0.001)");
                System.out.println("-C maximum learning cycle (default value is 10000)");
                      public static void main(String[] argv){
                            if(argv.length==0){
                                    System.out.println("Command line is <Java [-cp path] train parameters>");
                                    usage();
                                    System.exit(1);
                            if(argv.length==1 && argv[0].equals("help")==true){
                                    usage();
                                    System.exit(1);
                            par.nin(0); par.din(0); par.Rin(0.0); par.Cin(10000); par.Sin(0.001);
    for(int i=0;i<argv.length;i++){
                                            if(argv.equals("-f")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.fin(argv[i+1]);
    i++;
    else if(argv[i].equals("-d")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.din(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-n")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.nin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-S")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Sin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-C")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Cin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-R")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Rin(Double.parseDouble(argv[i+1]));
    i++;
    else error("Unkown token");
    check();
    try {
    dat.data();
    }catch(IOException e) { System.err.println(e.toString()); }
    try {
    mod.model();
    }catch(IOException e) { System.err.println(e.toString()); }
    try {
    resp.record();
    }catch(IOException e){ System.err.println(e.toString()); }

    String stringToRead=new String();
                    for(int i=0;i<=LineToRead.length();i++){
                            StringTokenizer str = new StringTokenizer (stringToRead,"/t");
                            String[] strtemp = new String[str.countTokens()];
                                    while (str.hasMoreTokens()){
                                    x[n][d++] = Double.parseDouble(str.nextToken());
                                    d++;
                                    System.out.println(x[n][d++]);
                            stringToRead=new String();
                    t[n]=Double.parseDouble(stringToRead);
                    x[n][par.d()]=1.0;
            }Not sure exactly what you are trying to do above but...
    You are setting your String to an empty String with "new String()" and then parsing that empty String. Eventually, you are trying to parse a double from that empty String:
    t[n]=Double.parseDouble(stringToRead);Also, I cannot think of a reason to ever use "new String()" when you could just use:
    String myString = "";

  • NumberFormatException problems. Thanks for the help

    Hi,
    Thanks for your help.
    I also tried using parseInt() method from Integer, but came up with the same exception:
    java.lang.NumberFormatException: 8
    from the line sets = sets.valueOf(buffed);
    Here is the code in question:
                                    String buffed;
                                    String cuffed = " ";
                                    Integer sets = new Integer(1);
                                    buffed = in.readLine();
                                    System.out.println(buffed);
                                    sets = sets.valueOf(buffed);
                                    int total = sets.intValue();System.out.println(buffed) pulls the string "8", as it should: the in.readLine() is using a dataOutputSteam type "in", and reads the line, which consists of 8 and ('/n').
    If anyone can offer a reason as to why this is happening, I'd be very grateful. Thanks for your time and consideration.
    chickenmuncher

    Hi,
    Thanks for the advice. Unfortunately, I confused myself, and I actually used the Buffered Reader object "in" and not the dataOutputStream object. Actually the file I'm reading is a txt file created by a dataOutputStream. This seems to create a buffer around the actual character so that when I do
                                    BufferedReader in = new BufferedReader();
                                    String unparsed = in.readLine();and say the txt line was output in the form
                                    DataOutputStream out = new dataOutputStream();
                                    String salsa = " ";
                                    out.writeChars(salsa.valueOf(count));
                                    out.writeChar('\n');, where int count = 8, I get back a string of length 3 such that
                                    char[] twisty;
                                    twisty = unparsed.toCharArray(); returns twisty[0] = "[
    twisty[1] = "8"
    and twisty[2] = "[
    This seems very odd to me. How do I get rid of the borders surrounding "8", and how did they get there in the first place?
    Again, thanks so much for the help, and sorry for the misdirection in the first question. Thanks for your time.
    dchickenmuncher

  • NumberFormatException resolving help

    I got a problem like,
    I have a string say "5.22".
    The existing code converts to Integer.parseInt("5.22").
    The code initially
    int j = Integer.parseInt("5.22";
    pstmt.setInt(2, j);
    Since it is not an Integer NumberFormatException occurs.
    The datatype of the value is NUMBER(5). I removed the Integer.parseInt and checked the but something like UNIQUE CONSTRAINT VIOLATION is coming.
    My fix
    float j = Float.parseFloat("5.22");
    pstmt.setFloat(2, j);
    error
    java.sql.SQLException: ORA-00001: unique constraint
    The value is not already present in the table I checked.
    Now I need help in,
    The datatype of the value in table 'NUMBER(5)' cannot be changed as it is common table for whole project. Is there any way to make the system accept the "5.22" as string then to float and then to Integer?
    The value 5.22 should not change while inserting into the table. I tried to convert float to int, Float.parseFloat nothing worked correctly.
    Edited by: 915175 on Aug 3, 2012 5:20 PM

    915175 wrote:
    I got a problem like,
    I have a string say "5.22".
    The existing code converts to Integer.parseInt("5.22").
    The code initially
    int j = Integer.parseInt("5.22";
    pstmt.setInt(2, j);
    Since it is not an Integer NumberFormatException occurs.
    The datatype of the value is NUMBER(5). I removed the Integer.parseInt and checked the but something like UNIQUE CONSTRAINT VIOLATION is coming.
    My fix
    float j = Float.parseFloat("5.22");
    pstmt.setFloat(2, j);
    error
    java.sql.SQLException: ORA-00001: unique constraint
    The value is not already present in the table I checked.
    Now I need help in,
    The datatype of the value in table 'NUMBER(5)' cannot be changed as it is common table for whole project. Is there any way to make the system accept the "5.22" as string then to float and then to Integer?
    The value 5.22 should not change while inserting into the table.
    The column is effectively defined as an integer. It will only accept integers. There is no way it will accept 5.22. Ever. In the end, you must either round or truncate 5.22.
    I tried to convert float to int, Float.parseFloat nothing worked correctly.You can pass it through various functions and transformations until the cows come home. But when the result finally gets to the INSERT, it must be an integer. Period.
    Edited by: 915175 on Aug 3, 2012 5:20 PMEdited by: EdStevens on Aug 3, 2012 7:32 AM

  • Can any one help me, im having a "java.lang.NumberFormatException: null"

    im doing a simple servlet and i got this error
    "java.lang.NumberFormatException: null"
    package process;
    * CreateCustomerServlet.java
    * Created on July 25, 2007, 10:04 AM
    import java.io.*;
    import java.net.*;
    import javax.annotation.Resource;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.DataSource;
    * @author SLI08
    * @version
    public class EnrollmentInfoServlet extends HttpServlet {
    @Resource(name = "School_system")
    private DataSource school_system;
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String Sch_term = null;
    String rmk = null;
    int Sch_year = 0;
    int enrollmentID = 0;
    int i_StudID = 1;
    String StudID = request.getParameter("StudentID");
    String sts = "";
    String msg="";
    //validate
    Connection conn = null;
    PreparedStatement pstmt = null;
    try{
    i_StudID = Integer.parseInt(StudID);
    conn = school_system.getConnection();
    pstmt = conn.prepareStatement("SELECT * FROM Enrollment WHERE StudentID=?");
    pstmt.setInt(1,i_StudID);
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()){
    enrollmentID=rs.getInt("EnrollmantID");
    Sch_year=rs.getInt("SchoolYear");
    Sch_term=rs.getString("SchoolTerm");
    rmk=rs.getString("Remark");
    sts=rs.getString("Status");
    HttpSession session = request.getSession();
    session.setAttribute("Enrollment",enrollmentID);
    session.setAttribute("SchoolYear",Sch_year);
    session.setAttribute("SchoolTerm",Sch_term);
    session.setAttribute("Remark",rmk);
    session.setAttribute("Status",sts);
    response.sendRedirect("testdisplay.jsp");
    }catch(SQLException ex){
    throw new ServletException(ex.getMessage());
    }finally{
    if(conn!=null) try{conn.close();}catch(SQLException e){}
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    // </editor-fold>
    }

    request.getParameter("StudentID");
    I think it maybe "null"
    test :
    if(request.getParameter("StudentID") == null)
    System.out.println("yes,it is null");i tried to comment out the "request.getParameter("StudentID")" and i put a default value of "1" which is present in my database and still i got the same error..

  • NumberFormatException plz help...

    have encountered a NumberformatException and I am giving stacktrace
    at java.lang.NumberFormatException. 0(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:415)
    at java.lang.Long.<init>(Long.java:630)
    at domaintt.main(domaintt.java:29)
    It occurs in the given statement
    Long duration =new Long(form.getDuration()) /* getDuration() returns a string which is equal to no of hours */
    I want to replicate this Exception with some sample data.I.e like
    Long l = new Long("uuu");
    I am able to produce the Exception but in some other format like
    java.lang.NumberFormatException: For input string: "uuu"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:415)
    at java.lang.Long.<init>(Long.java:630)
    at domaintt.main(domaintt.java:29)
    if i give
    Long l =new Long("0"); it's not thowing exception as expected.Then in what scenario
    java.lang.NumberFormatException. 0(NumberFormatException.java:48)
    will occur.I am unable to replicate and i do not understand In case of '0'
    how it will thowing exception.
    I am wondering why in case '0' it is throwing Exception and any way I am passing string as parameter.so Stack trace should be as
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:415)
    at java.lang.Long.<init>(Long.java:630)
    at domaintt.main(domaintt.java:29)
    but it is not like that.
    Thanks,
    kanth.

    You already asked this question here: http://forum.java.sun.com/thread.jspa?threadID=673153
    Don't start another thread for the same question.
    kind regards,
    Jos

  • NumberFormatException help!!!URGENT

    I have a problem:
    I read a String from JTextArea, this string like "e4ff56...", after a parse I can obtain strings like "e4", "ff", "56",....
    These strings are hexdecimal nembers, of course. So I need to define this strings as byte types, in particular to build a byte array from these strings (byte[] data = {0xe4, 0xff, 0x56,...}.
    Someone knows how to do it?
    This is very important!!!
    Thanks in advance!

    I have a problem:
    I read a String from JTextArea, this string like
    "e4ff56...", after a parse I can obtain strings like
    "e4", "ff", "56",....
    These strings are hexdecimal nembers, of course. So I
    need to define this strings as byte types, in
    particular to build a byte array from these strings
    (byte[] data = {0xe4, 0xff, 0x56,...}.
    Someone knows how to do it?
    This is very important!!!
    Thanks in advance!Hi,
    Will this do? String s = "e4";
    byte b = (byte) Integer.parseInt(s,16);You might want to check ranges..

  • Java.lang.NumberFormatException: For input string: "DESCRIPTION="

    Colleagues,
    eBis 11.5.10.2.
    I'm getting a Warning in the concurrent manager when I submit a programme that has an attached xml template. The warning is stating: -
    ------------- 1) PUBLISH -------------
    Beginning post-processing of request 2667735 on node BAMBI at 02-SEP-2011 17:32:56.
    Post-processing of request 2667735 failed at 02-SEP-2011 17:32:57 with the error message:
    One or more post-processing actions failed. Consult the OPP service log for details.
    ------------- 2) PRINT   -------------
    Not printing the output of this request because post-processing failed.
    When I consult the OPP log in Sysadmin, I can see a not very helpful message: -
    [9/2/11 5:32:57 PM] [UNEXPECTED] [36822:RT2667735] java.lang.NumberFormatException: For input string: "DESCRIPTION="
         at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         at java.lang.Integer.parseInt(Integer.java:447)
         at java.lang.Integer.parseInt(Integer.java:497)
         at oracle.apps.xdo.generator.pdf.PDFGenerator.setFont(PDFGenerator.java:629)
         at oracle.apps.xdo.generator.pdf.PDFGenerator.setProperties(PDFGenerator.java:468)
         at oracle.apps.xdo.generator.ProxyGenerator.setProperties(ProxyGenerator.java:1373)
         at oracle.apps.xdo.template.fo.FOHandler.startElement(FOHandler.java:262)
         at oracle.apps.xdo.template.fo.FOHandler.startElement(FOHandler.java:204)
         at oracle.apps.xdo.common.xml.XSLTMerger.startElement(XSLTMerger.java:55)
         at oracle.xml.parser.v2.XMLContentHandler.startElement(XMLContentHandler.java:167)
         at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1182)
         at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
         at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
         at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:149)
         at oracle.apps.xdo.template.fo.FOProcessingEngine.process(FOProcessingEngine.java:320)
         at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:1051)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.runProcessTemplate(TemplateHelper.java:5926)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3458)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3547)
         at oracle.apps.fnd.cp.opp.XMLPublisherProcessor.process(XMLPublisherProcessor.java:290)
         at oracle.apps.fnd.cp.opp.OPPRequestThread.run(OPPRequestThread.java:157)
    [9/2/11 5:32:57 PM] [36822:RT2667735] Completed post-processing actions for request 2667735.
    Now, this isn't programme specific as it's affecting all our BI Publisher reports. Also the specific report I am working on has the option to email. I'm finding that the emails still work and when I open the attachment, they are displaying in PDF format correctly - even though the concurrent manager completes with the above warning. The above warning doesn't let me view the output in PDF from Oracle Financials.
    Any help would be greatly appreciated.
    Thanks

    Maybe check if Metalink note 764180.1 applies? This appears to be a bug fixed with patch 7669965.

  • Jsp throw numberformatexception.see my code .reply as soon as possible

    i am developed application onclick checkbox delete the record.on first field i give the href to serailno for open the update page. like this <a href="UpdateBoq.jsp?S_NO=<%=sno%>">.sno is serialno.is come from database wihen i am click on serial no it show the updatepage.jsp is not open the updatepage.jsp but it throw the exception number format.this is my code.anybody help me this my project working i am only the single persion to develop this application in jsp.please help me.as soon as possible
    <%@ page language="java" import="java.sql.*"%>
    <%@ page import="java.text.SimpleDateFormat" %>
    <%@ page import="java.util.Date" %>
    <%! int count = 0; %>
    <%! String itemcode;%>
    <%! String sns;%>
    <%! String contunit; %>
    <%! float qty; %>
    <%! float oup;%>
    <%! float oep;%>
    <%! int sno;%>
    <%! int stcode;%>
    <%! float sum=0.0f;%>
    <%! float sum1=0.0f;%>
    <jsp:useBean id="sos" class="boq.Calculation" scope="request"/>
    <%
    //String userID = String.valueOf(session.getAttribute("APP_USER_ID"));
    //String userID = String.valueOf(session.getAttribute("LOGIN_ID"));
    String strDelete = request.getParameter("btnDelete");
    String strserialno=request.getParameter("serialno1");
    String strmopno = request.getParameter("mop");
    String strjobno = request.getParameter("job");
    String strwop=request.getParameter("siten");
    String strno=request.getParameter("siteno");
    if (strDelete != null)
    String del=request.getParameter("hidcount");
    int delcount=-1;
    if (del!=null)
    System.out.println("I am in start of delete Action");
    delcount = Integer.parseInt(del);
    String strCheckBox="";
    String strHidVal="";
    for (int i=0; i<=delcount; i++)
    strCheckBox = request.getParameter("checkbox"+i);
    if(strCheckBox!=null)
    strHidVal = request.getParameter("hid"+i);
    System.out.println("country code is :"+strHidVal);
    System.out.println(del);
    Connection con=null;
    try
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.87:1521:orcl","system","tiger");
    System.out.println(con);
    Statement st2 = con.createStatement();
    Statement st1 = con.createStatement();
    String str0="select * from BOQ where S_NO= '"+ strHidVal + "'";
    ResultSet rs = st1.executeQuery(str0);
    String str="delete from BOQ where S_NO= '"+ strHidVal + "'";
    System.out.println(strCheckBox);
    int a=st2.executeUpdate(str);
    catch(Exception e)
    %>
    <script language="JavaScript">
    alert("<%=e.getMessage()%>");
    </script>
    <%
    finally
    if(con!=null)
    con.close();
    %>
    <html>
    <head>
    <title>CRS</title>
    <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
    <link rel="stylesheet" href="css/ems.css" type="text/css">
    </HEAD>
    <body leftmargin=0 topmargin=2>
    <jsp:include page="Index.html" />
    <form name=form1 action="BOQVIEW.jsp" method=post>
    <table border=0 cellspacing=1 cellpadding=1 width=100% height=5>
    <tr>
    <td valign="top" height="23">
    <table width="100%" border="0" cellspacing="1" cellpadding="1">
    <tr>
    <td bgcolor='#E6E4E4' width=45 align="Center" colspan=2>
    <font color="#5d7a80" size="2">
    BOQ OF MOPS
    </font>
    </td>
    </tr>
    </table>
    </td>
    </tr>
    <tr>
    <td valign=top>
    <table width="100%" cellpadding="1" cellspacing="1" border="0">
    <tr>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=40>S/NO</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=60>SITE NAME</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=65>SITE NUMBER</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=90>ITEM CODE/MATERIAL CODE</td>
    <td width="180" height="5" class="ReportColumnHeader" align="center"colspan=120>CONTRACT UNIT DESCRIPTION ORIGINAL</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=>QUANTITY</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=90 >ORIGINAL UNIT PRICE</td>
    <td width="130" height="5" class="ReportColumnHeader" align="center" colspan=100>ORIGINAL EXTENDED PRICE</td>
    </tr>
    </table>
    <%
    Connection con=null;
    try
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","tiger");
    System.out.println(con);
    Statement st = con.createStatement();
    Statement st1=con.createStatement();
    String qoq=request.getParameter("qoq");
    int one=Integer.parseInt(qoq);
    ResultSet rs = st.executeQuery("SELECT * from BOQ where SITE_CODE="+one);
    ResultSet rs1=st1.executeQuery("select SUM(O_U_P) AS oriunitprice,SUM(O_E_P) AS oriextendsprice from boq WHERE SITE_CODE="+one);
    %>
    <%
    int count=0;
    while(rs.next())
    sno=rs.getInt(1);
    stcode=rs.getInt(2);
    sns=rs.getString(3);
    itemcode=rs.getString(4);
    contunit = rs.getString(5);
    qty=rs.getFloat(6);
    oup = rs.getFloat(7);
    oep = rs.getFloat(8);
    %>
    <table border="0" cellspacing="1" cellpadding="1" width="100" >
    <tr>
    <td class="ReportCellText1" width="10" height=><input type=checkbox name="<%="checkbox"+count%>" onselect="deleterecord();"> </td>
    <td class="ReportCellText1" width="130" height="5" align="center" colspan=29><a href="UpdateBoq.jsp?S_NO=<%=sno%>"><%=sno%></a>
    </td>
    <td class="ReportCellText1" width="55" height="5" align="center" COLSPAN=60><%=sns%></td>
    <td class="ReportCellText1" width="50" height="5" align="center" COLSPAN=65><%=stcode%></td>
    <td class="ReportCellText1" width="130" height="5" align="center" COLSPAN=90><%=itemcode%></td>
    <td class="ReportCellText1" width="130" height="5" align="center" COLSPAN=120><%=contunit%></td>
    <td class="ReportCellText1" width="130" height="5" align="center" COLSPAN=54><%=qty%></td>
    <td class="ReportCellText1" width="130" height="5" align="center" COLSPAN=90><%=oup%></td>
    <td class="ReportCellText1" width="130" height="5" align="center" colspan=100> <%=oep%></td>
    </tr>
    <tr>
    </table>
    <input type=hidden name="<%="hid"+count%>" value="<%=sno%>">
    <!--
    </tr>
    <tr>
    </tr>
    <tr>
    </tr> !-->
    <%
    count++;
    %>
    <table width="100%" cellpadding="1" cellspacing="1" border="0">
    <TR>
    <td width="60" height="5" class="ReportCellText3" align="center" colspan=></td>
    <td class="ReportCellText3" width="55" height="5" align="center" COLSPAN=></td>
    <td width="60" height="5" class="ReportCellText3" align="center" colspan=></td>
    <td class="ReportCellText3" width="50" height="5" align="center" COLSPAN=></td>
    <td class="ReportCellText3" width="50" height="5" align="center" COLSPAN=></td>
    <td class="ReportCellText3" width="50" height="5" align="center" COLSPAN=></td>
    <td class="ReportCellText3" width="50" height="5" align="center" COLSPAN=></td>
    <%
    rs1.next();
    sum=rs1.getFloat("oriunitprice");
    sum1=rs1.getFloat("oriextendsprice");
    %>
    <td width="60" height="5" class="ReportColumnHeader" align="center" colspan=>TOTLE AMOUNT</td>
    <td class="ReportCellText1" width="85" height="5" align="center" colspan=> <%=sum%></td>
    <td class="ReportCellText1" width="90" height="5" align="center" colspan=> <%=sum1%></td>
    </table>
    <TABLE>
    <input type=hidden name=hidcount value =<%=count%>>
    <input type=hidden name=serialno value=<%=itemcode%>>
    <INPUT TYPE=hidden NAME=mop VALUE=<%=contunit%> >
    <INPUT TYPE=hidden NAME=job VALUE=<%=qty%> >
    <INPUT TYPE=HIDDEN name=siten value=<%=oup%>>
    <input type=hidden name=siteno value=<%=oep%>>
    <table><tr><td>
    <input type = button value = Print size=20 onClick = "window.print();"></td>
    <td><input type = Submit value = "Delete" name="btnDelete" size = 20> </td>
    </form>
    <form action=BOQ.jsp method=post>
    <td><input type=Submit value = "Add New" size=20></td>
    </form>
    <form action=NEWPEexl.jsp method=post>
    <td><input type=Submit value = "Export to Excel" size=20></td></tr></table>
    </form>
    <%
    catch(Exception e)
    out.println(e.getMessage());
    finally
    if(con!=null)
    con.close();
    %>
    </body>
    </html>
    when i am click the serial no it show the update page is update .jsp
    this is the update code
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/fileaccess.tld"
    prefix="fileaccess"%>
    <%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/sqltaglib.tld"
    prefix="database"%>
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page language="java" import="java.sql.,java.util."%>
    <%@ page import="java.text.SimpleDateFormat" %>
    <%@ page import="java.util.Date" %>
    <%! int count = 0; %>
    <%!Connection con=null;%>
    <%!PreparedStatement ps=null;%>
    <%
    String strUpdate = request.getParameter("btnUpdate");
    String sno=request.getParameter("serialno1");
    int snoi=Integer.parseInt(request.getParameter("serialno1"));
    String sc=request.getParameter("sitenumber");
    int sci=Integer.parseInt(request.getParameter("sitenumber"));
    String sn=request.getParameter("sitename");
    String itc=request.getParameter("itemno");
    String cu=request.getParameter("contract");
    String qty=request.getParameter("quantity");
    float qtyf=Float.parseFloat(request.getParameter("quantity"));
    String oup=request.getParameter("orig");
    float oupf=Float.parseFloat(request.getParameter("orig"));
    String oep=request.getParameter("origexp");
    float oepf=Float.parseFloat(request.getParameter("origexp"));
    if (strUpdate != null)
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.87:1521:orcl","system","tiger");
    System.out.println(con);
    System.out.println("Connection Established");
    Statement st = con.createStatement();
    String str="update BOQ set SITE_CODE="sci",SITE_NAME='"sn"',ITEM_CODE='"itc"',CONTRACT_UNIT='"cu"',QTY="qtyf",O_U_P="oupf",O_E_P="oepf" where S_NO="snoi" ";
    int a=st.executeUpdate(str);
    if (a>0)
    %>
    <script type="text/javascript" >
    alert("The Record has been Updated Successfully");
    <% response.sendRedirect("BOQVIEW.jsp"); %>
    </script>
    <%
    catch(Exception e)
    String m = e.getMessage();
    %>
    <font size="1" face="Verdana" color=blue>
    "<%=m%>"</font>
    <%
    try
    if(con!=null)
    con.close();
    catch(SQLException sq)
    out.println(sq.getMessage());
    %>
    <!-- Insert the data code-->
    <HTML>
    <head>
    <title>BOQ</title>
    <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
    <script type="text/javascript">
    function callingdate()
    Calendar.setup({
    inputField : "f_date_b", //*
    ifFormat : "%d-%b-%Y ",
    showsTime : true,
    button : "f_trigger_b", //*
    step : 1
    function callingdate1()
    Calendar.setup({
    inputField : "f_date_b1", //*
    ifFormat : "%d-%b-%Y ",
    showsTime : true,
    button : "f_trigger_b1", //*
    step : 1
    function dating()
    var mylist=document.getElementById("effective_date")
    document.getElementById("date").value=mylist.options[mylist.selectedIndex].text
    function caps() {
    document.form1.country_code.value = document.form1.country_code.value.toUpperCase()
    document.form1.country_name.value = document.form1.country_name.value.toUpperCase()
    </script>
    </head>
    <BODY >
    <% count++;
    %>
    <form name=form1 action=UpdateBoq.jsp method=post>
    <!-- <h3 STYLE = "BACKGROUND-COLOR=blue;
    COLOR=YELLOW"
    align=center color=green>Country Information</h1> !-->
    <table width="100%" border="0" cellspacing="1" cellpadding="0">
    <tr>
    <td bgcolor='#336699' align="Center"><font color="#d2b48c" size=2>BOQ OF MOPS</font> </td>
    </tr>
    </table>
    <%
    Connection con=null;
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.87:1521:orcl","system","tiger");
    System.out.println(con);
    Statement st = con.createStatement();
    String se=request.getParameter("serialno1");
    //int ser=Integer.parseInt(request.getParameter("serialno1"));
    String s="SELECT * from BOQ where S_NO="Integer.parseInt(request.getParameter("serialno1"))" ";
    ResultSet rs = st.executeQuery(s);
    System.out.println(s);
    %>
    <%
    while(rs.next())
    int serialno=rs.getInt(1);
    int stcode=rs.getInt(2);
    String sname=rs.getString(3);
    String itcode=rs.getString(4);
    String conunit=rs.getString(5);
    float qtyw = rs.getFloat(6);
    float oupw=rs.getFloat(7);
    float oepw=rs.getFloat(8);
    %>
    <table width="100%" border="0" cellspacing="1" cellpadding="0">
    <tr>
    <td bgcolor='#E6E4E4' align="Center" width=100%><font color="#5d7a80" size=2>BOQ OF MOPS </font> </td>
    </tr>
    </table>
    <table width="100%" border="0" cellspacing="1" cellpadding="0">
    <tr><td >
    1)SERIAL NUMBER:</td><td><input type=text name=serialno1 value= "<%=serialno%>" size=10 onblur = "caps();">
    </td></tr>
    <tr><td >
    2)SITE NUMBER:</td><td><input type=text name=sitenumber value= "<%=stcode%>" size=10 onblur = "caps();">
    </td></tr>
    <tr><td >
    3)SITE NAME:</td><td><input type=text name=sitename value= "<%=sname%>" size=10 onblur = "caps();">
    </td></tr>
    <tr><td>
    4)ITEM CODE/MATERIAL CODE:</td><td><input type=text name=itemno value= "<%=itcode%>" size = 20 onblur = "caps();" >
    </td></tr>
    <tr><td>
    5)CONTRACT UNIT DESCRIPTION:</td><td><input type=text name=contract value= "<%=conunit%>" size = 20 onblur = "caps();" >
    </td></tr>
    <tr><td>
    6)QUANTITY:</td><td><input type="text" name="quantity" value= "<%=qtyw%>" size =40 onblur = "caps();" >
    </td></tr>
    <tr><td>
    7)ORIGNAL UNIT/PRICE:</td><td><input type=text name=orig value= "<%=oupw%>" size = 20 onblur = "caps();" >
    </td></tr>
    <tr><td>
    8)ORIGNAL EXTENDED/PRICE:</td><td><input type=text name=origexp value= "<%=oepw%>" size = 20 onblur = "caps();" >
    </td></tr>
    </TABLE>
    <%
    %>
    <center>
    <table>
    <tr><td>
    <INPUT TYPE=Submit value = Update name="btnUpdate" size=20/></td> </tr></table>
    </form>
    <form action="BOQVIEW.jsp" method = post>
    <center> <table>
    <tr><td>
    <input type="submit" value="View" size="20"></input>
    </td> </tr></table>
    </form>
    </form>
    </table>
    </center>
    <hr>
    <script type="text/javascript">
    Calendar.setup({
    inputField : "f_date_b", //*
    ifFormat : "%d-%b-%Y ",
    showsTime : false,
    button : "f_trigger_b", //*
    step : 1
    Calendar.setup({
    inputField : "f_date_b1", //*
    ifFormat : "%d-%b-%Y",
    showsTime : false,
    button : "f_trigger_b1", //*
    step : 1
    </script>
    </BODY>
    <%
    catch(Exception e)
    out.println(e.getMessage());
    finally
    try
    if(con!=null)
    con.close();
    catch(SQLException sq)
    out.println(sq.getMessage());
    %>
    </HTML>
    this my table database oracle 9i
    CREATE TABLE BOQ
    S_NO INTEGER NOT NULL,
    SITE_CODE INTEGER,
    SITE_NAME VARCHAR2(40),
    ITEM_CODE VARCHAR2(20),
    CONTRACT_UNIT VARCHAR2(60),
    QTY FLOAT(70),
    O_U_P FLOAT(70),
    O_E_P FLOAT(70)
    );</a>

    1. Use code tags, there's button that says 'Code'. Select your text and use that. I'm not going to read your code while it's unformatted like this and especially because you seem to have posted your whole darn project here; and I suspect few others will bother either.
    2. Don't paraphrase the exception; post the exact stack trace.
    3. There's usually a line number given with the exception; which line does your stack trace point to? Try to figure out what you're doing wrong there.
    4. NumberFormatException means that you're trying to parse a string that's not in the correct format. Make sure the data you're getting from the DB is correct.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    ----------------------------------------------------------------

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • Can you help me with my program please?

    hi all,
    I have a problem with the sellMilk function at the Milk class I don't know how to write it right I've tried everything so I need you to help me.
    this function should check the expiry date of the milk and sell the required amount if it is not expired. if it was expired just delete the milkbox.
    I have cases like if the first box has 5 kg and not expired , second box has 10 kg and expired, third box has 8 kg and not expired .. and if the required amount to sell is 6 kg for example it should work like this: first box should become zero because 5 kg has been sold and remainder is 1 .. so it should check the expiry date of the second box and it is expired so delete it. and then check the third box's expiry date and it is not expired so 8-1 = 7 .. and by that way 6 kg has been sold.
    my program it just delete the expired box if it was the first element.
    my code doesn't work well like that! here is the full program so you can check the code to help me please ..
    the problem is just with SellMilk() at the Milk Class
    Thank you
    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class Market
        public static void main(String args[ ])
        { System.out.print("Enter the Market name: " );
            String name1 = Stdin.readLine();
            Market_Store mymarketstore = new Market_Store(name1);
       System.out.println("Welcome To " +name1+" Market ");
       System.out.println("");
            System.out.println("1-Stock new Milk");
            System.out.println("2-Stock new Milk Box");
            System.out.println("3-Sell");
            System.out.println("4- Display");
            System.out.println("");
            System.out.print("Enter your choice: ");
            int choice = Stdin.readInteger();
            while (choice != 5)
                switch (choice)
                case 1:
                 mymarketstore.stockNewMilk();
                    break;
                case 2:
                    mymarketstore.stockMilkBox();
                    break;
                    case 3:
             mymarketstore.sell();
                break;
                case 4:
               mymarketstore.display();
                            break;
                            case 5:
                default:
                    System.out.println("wrong Number");
                    System.out.println("Enter a number between 1 to 4 ");
                    System.out.println("Enter 5 to Exit");
                    break;
                System.out.println("");
              System.out.println("Welcome To " +name1+" Market ");
       System.out.println("");
            System.out.println("1-Stock new Milk");
            System.out.println("2-Stock new Milk Box");
            System.out.println("3-Sell");
            System.out.println("4-Display");
            System.out.println("");
             System.out.print("Enter your choice: ");
                choice = Stdin.readInteger();
    class Market_Store
            private String name;
            private Vector mymilk;
            public Market_Store(String n)
                    name=n;
                    mymilk = new Vector();
            public void stockNewMilk()
                    String N;//milk type
                    System.out.print("Enter the type of the milk: ");
                    N=Stdin.readLine();
                    Milk  m1 = new Milk (N);
                    mymilk.addElement(m1);
            public void stockMilkBox()
            System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());  }
                    System.out.print("Enter the number of the milk to stock new box: ");
            int     ii = Stdin.readInteger();
            ((Milk)(mymilk.elementAt(ii-1))).addNewBox();
            }//end stockMilkBox
            public void sell()
                    //sell specific type of milk
                   System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());
                                   System.out.print("Enter the number of the milk to sell:  ");
            int     ii = Stdin.readInteger();
    System.out.print("Enter the amount required in Kg:  ");
    double amount = Stdin.readDouble();
            ((Milk)(mymilk.elementAt(ii-1))).sellMilk(amount);
            public void display()
            {      System.out.println("Milk Available in stock : ");
            for (int i=0; i<mymilk.size(); i++){
            Milk m2 = (Milk)mymilk.elementAt(i);
            System.out.print(i+1+")");
            System.out.println(m2.getMilkType());
                    System.out.print("Enter the number of the milk to display:  ");
            int     ii = Stdin.readInteger();
                    ((Milk)(mymilk.elementAt(ii-1))).display();
    class MilkBox
            private Date expiredate;
            private Date date;
            private double stock;
            public MilkBox(double stck, Date ed)
                     date = new Date();
                    expiredate = ed;
            public double getStock()
             return stock;     }
            public Date getDate()
                     return date;
    public void setStock(double st)
    { stock = st;}
    public void setExDate(Date dd)
    {expiredate = dd;}
            public Date getExDate()
                     return expiredate;
      public   double sellMilkBox(double amount)
            double excessAmount = 0;
            if (amount < stock)
                double newAmount = stock - amount;
                setStock(newAmount);
            else  
                excessAmount = amount - stock;
                setStock(0);
            return excessAmount;
    public     void display()
                            System.out.println("The box of "+date+" has " +stock+" KG");
    class Milk
            private String Mtype;//milk type
            private Vector mybox;//vector of batches
            public Milk (String n)
                    Mtype =n;
            mybox = new Vector();
      public  void addNewBox()
    double stook;
    System.out.print("Enter the weight of the box: ");
    stook = Stdin.readDouble();
         Date exdate;//expirey date
    System.out.println("Enter the expirey date of the milk box:");
           int d; int m1; int y;
              System.out.println("Enter Year:" );
              y = Stdin.readInteger();
              System.out.println("Enter Month:" );
              m1 = Stdin.readInteger();
              System.out.println("Enter Day:" );
              d = Stdin.readInteger();
                   Calendar r=new GregorianCalendar(y,m1,d);
                    exdate= r.getTime();
                    //send the attributes to Box constructor
                   MilkBox newBox = new MilkBox(stook,exdate);
                    newBox.setStock(stook);
                    newBox.setExDate(exdate);
                    mybox.addElement(newBox);
       public void display()
                    System.out.println("Milk "+Mtype);
                            for (int i=0; i<mybox.size(); i++){
                    MilkBox b= (MilkBox)mybox.elementAt(i);
                    b.display();
    public double sellMilk (double amount)
       for(int i=0;i<mybox.size();i++)
               MilkBox b = (MilkBox)mybox.elementAt(i);
                double stock = b.sellMilkBox(amount);
                double value = b.getStock();
                Date ExpireyDate = b.getExDate();
      if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
    if (stock >1|| value  ==  0 && ExpireyDate.after(new Date()))
    {       mybox.remove(b);  
    amount = stock;
    if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
      if(amount != 0)
      System.out.println("The extra amount is "+amount+ " KG");
    return amount;}
    public String getMilkType()
    { return Mtype;}
    //set method
    void setMilkType(String n)
    { Mtype = n;}
    }//end class milk
    //STDIN FILE
    final class Stdin
       public static BufferedReader reader=new BufferedReader
        (new InputStreamReader(System.in));
       public static String readLine()
       while(true)
       try{
           return reader.readLine();
           catch(IOException ioe)
             reportError(ioe);
           catch(NumberFormatException nfe)
            reportError(nfe);
       public static int readInteger()
        while(true)
        try{
        return Integer.parseInt(reader.readLine());
        catch(IOException ioe)
        reportError(ioe);
        catch(NumberFormatException nfe)
        reportError(nfe);
       public static double readDouble()
        while(true)
        try{
        return Double.parseDouble(reader.readLine());
        catch(IOException ioe)
        reportError(ioe);
        catch(NumberFormatException nfe)
        reportError(nfe);
        public static void reportError (Exception e)
        System.err.println("Error input:");
        System.err.println("please re-enter data");
        }Edited by: mshadows on Dec 22, 2007 12:06 AM

    ok here is the code that has the problem .. what's wrong with it?
    public double sellMilk (double amount)
       for(int i=0;i<mybox.size();i++)
               MilkBox b = (MilkBox)mybox.elementAt(i);
                double stock = b.sellMilkBox(amount);
                double value = b.getStock();
                Date ExpireyDate = b.getExDate();
      if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
    if (stock >1|| value  ==  0 && ExpireyDate.after(new Date()))
    {       mybox.remove(b);  
    amount = stock;
    if ( ExpireyDate.before(new Date()))
    {  mybox.removeElementAt(i);
            System.out.println("it has expired date");
      if(amount != 0)
      System.out.println("The extra amount is "+amount+ " KG");
    return amount;}

  • Can anyone help me, please(again)

    Hello :
    I am sorry that my massage is not clearly.
    Please run my coding first, and get some view from my coding. you can see somes buttons are on the frame.
    Now I want to click the number 20 of the buttons, and then I want to display a table which from the class TableRenderDemo to sit under the buttons. I added some coding for this problem in the class DrawClalendar, the coding is indicated by ??.
    but it still can not see the table apear on on the frame with the buttons.
    Can anyone help me to solve this problem.please
    Thanks
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
        private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
               setLayout(gL);
               assignValues();
               addJButton();
               registerListener();
        //assign values to each button
           private void assignValues(){
              names = new String[35];
             for(int i = 0; i < names.length; i++)
                names[i] = Integer.toString(i + 1);
         //create buttons and add them to Jpanel
         private void addJButton(){
              buttons=new JButton[names.length];
              for (int i=0; i<names.length; i++){
                   buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
         if(i==20){  //???????????               
              tM=new TestMain(); //???????
              tM.c.removeAll(); //??????
              tM.c.add(dC); //???????
              tM.c.add(myTable); //????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
    private boolean DEBUG = true;
    public TableRenderDemo() {
    // super("TableRenderDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
    //Create the scroll pane and add the table to it.
    setViewportView(table);
    //Set up column sizes.
    initColumnSizes(table, myModel);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
         private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     

    I think this is what you are trying to do. Your code was not very clear so I wrote my own:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableButtons extends JFrame implements ActionListener
         Component southComponent;
        public TableButtons()
              JPanel buttons = new JPanel();
              buttons.setLayout( new GridLayout(5, 7) );
              Dimension buttonSize = new Dimension(20, 20);
              for (int j = 0; j < 35; j++)
                   // this is a trick to convert an integer to a string
                   String label = "" + (j + 1);
                   JButton button = new JButton( label );
                   button.setBorder( null );
                   button.setBackground( Color.white );
                   button.setPreferredSize( buttonSize );
                   button.addActionListener( this );
                   buttons.add(button);
              getContentPane().add(buttons, BorderLayout.NORTH);
         public void actionPerformed(ActionEvent e)
              JButton button = (JButton)e.getSource();
              String command = button.getActionCommand();
              if (command.equals("20"))
                   displayTable();
              else
                   System.out.println("Button " + command + " pressed");
                   if (southComponent != null)
                        getContentPane().remove( southComponent );
                        validate();
                        pack();
                        southComponent = null;
         private void displayTable()
            String[] columnNames = {"Student#", "Student Name", "Gender", "Grade", "Average"};
            Object[][] data =
                {new Integer(1), "Bob",   "M", "A", new Double(85.5) },
                {new Integer(2), "Carol", "F", "B", new Double(77.7) },
                {new Integer(3), "Ted",   "M", "C", new Double(66.6) },
                {new Integer(4), "Alice", "F", "D", new Double(55.5) }
            JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane= new JScrollPane( table );
            getContentPane().add(scrollPane, BorderLayout.SOUTH);
            validate();
            pack();
            southComponent = scrollPane;
        public static void main(String[] args)
            TableButtons frame = new TableButtons();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Can anyone help me, please

    Hello again:
    Please run my coding first, and get some view from my coding.
    I want to add a table(it is from TableRenderDemo) to a JFrame when I click on the button(from DrawCalendar) of the numer 20, and I want the table disply under the buttons(from DrawCalendar), and the table & buttons all appear on the frame. I added some code for this problem(in the EventHander of the DrawCalendar class), but I do
    not known why it can not work.Please help me to solve this problem.
    Can anyone help me, please.
    Thanks.
    *This program for add some buttons to JPanel
    *and add listeners to each button
    *I want to display myTable under the buttons,
    *when I click on number 20, but why it doesn't
    *work, The coding for these part are indicated by ??????????????
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GridLayout;
    public class DrawCalendar extends JPanel {
         private static DrawCalendar dC;
         private static TestMain tM;
         private static TableRenderDemo myTable;
         private static GridLayout gL;
         private static final int nlen = 35;
        private static String names[] = new String[nlen];
        private static JButton buttons[] = new JButton[nlen];
         public DrawCalendar(){
              gL=new GridLayout(5,7,0,0);
               setLayout(gL);
               assignValues();
               addJButton();
               registerListener();
        //assign values to each button
           private void assignValues(){
              names = new String[35];
             for(int i = 0; i < names.length; i++)
                names[i] = Integer.toString(i + 1);
         //create buttons and add them to Jpanel
         private void addJButton(){
              buttons=new JButton[names.length];
              for (int i=0; i<names.length; i++){
                   buttons=new JButton(names[i]);
         buttons[i].setBorder(null);
         buttons[i].setBackground(Color.white);
         buttons[i].setFont(new Font ("Palatino", 0,8));
    add(buttons[i]);
    //add listeners to each button
    private void registerListener(){
         for(int i=0; i<35; i++)
              buttons[i].addActionListener(new EventHandler());          
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
    private class EventHandler implements ActionListener{
         public void actionPerformed(ActionEvent e){
         for(int i=0; i<35; i++){
    //I want to display myTable under the buttons,
    //when I click on number 20, but why it doesn't
    //work
         if(i==20){  //???????????               
              tM=new TestMain(); //???????
              tM.c.removeAll(); //??????
              tM.c.add(dC); //???????
              tM.c.add(myTable); //????
              tM.validate();
         if(e.getSource()==buttons[i]){
         System.out.println("testing " + names[i]);
         break;
    *This program create a table with some data
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableRenderDemo extends JScrollPane {
    private boolean DEBUG = true;
    public TableRenderDemo() {
    // super("TableRenderDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(700, 70));//500,70
    //Create the scroll pane and add the table to it.
    setViewportView(table);
    //Set up column sizes.
    initColumnSizes(table, myModel);
    //Fiddle with the Sport column's cell editors/renderers.
    setUpSportColumn(table.getColumnModel().getColumn(2));
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table, MyTableModel model) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.longValues;
    for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    try {
    comp = column.getHeaderRenderer().
    getTableCellRendererComponent(
    null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    } catch (NullPointerException e) {
    System.err.println("Null pointer exception!");
    System.err.println(" getHeaderRenderer returns null in 1.3.");
    System.err.println(" The replacement is getDefaultRenderer.");
    comp = table.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(
    table, longValues[i],
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Chasing toddlers");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Teaching high school");
    comboBox.addItem("None");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = sportColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary ", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    //With JFC/Swing 1.1 and JDK 1.2, we need to create
    //an Integer from the value; otherwise, the column
    //switches to contain Strings. Starting with v 1.3,
    //the table automatically converts value to an Integer,
    //so you only need the code in the 'else' part of this
    //'if' block.
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(TableRenderDemo.this,
    "The \"" + getColumnName(col)
    + "\" column accepts only integer values.");
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    *This program for add some buttons and a table on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class TestMain extends JFrame{
    private static TableRenderDemo tRD;
         private static TestMain tM;
    protected static Container c;
    private static DrawCalendar dC;
         public static void main(String[] args){
         tM = new TestMain();
         tM.setVisible(true);
         public TestMain(){
         super(" Test");
         setSize(800,600);
    //set up layoutManager
    c=getContentPane();
    c.setLayout ( new GridLayout(3,1));
    tRD=new TableRenderDemo();
    dC=new DrawCalendar();
    addItems();//add Buttons to JFrame
    private void addItems(){
         c.add(dC); //add Buttons to JFrame
         //c.add(tRD); //add Table to JFrame     

    Click Here and follow the steps to configure your Linksys Router with Version FIOS.

  • A CRY OF Help..To All Java Programmer

    Iam desperate please help....I Have to finish this code until tommorrow...i have done some and its running but it doesnt show the right computation...
    Prob:
    Mail order house sells 5 different product..prod1-$2.98, prod2-$4.50, prod3- $9.98, prod4- $4.49 and prod 5- $6.87..Write an application that reads a series of pairs of numbers as follows:
    a)Product number
    b)Quantity sold for one day
    Program should use a switch structure to help determine the retail price for each product.Your program should calculate and display total retail value of all product sold last week. Use a TextField to obtain the product number from the user. Use sentinel -controlled loop to determine when the product should stop looping and display final results.
    Note: I change temporarily the product because I am not familiar with double data types..
    this is the code i have currently done..Please.please.please i need all the help..
    import javax.swing.JOptionPane;
    import java.text.DecimalFormat;
    public class ProbMod {
         public static void main( String args[] )
              int quant,
                   prodnum,
                   Counter,total,input,lahatna,prodquan,
                   gtotal;           
              double      
                        average;
              String
                        num1,
                        num2;
              total = 0;
              Counter = 0;
              gtotal = 1;
              input = 0;
              lahatna = 0;
              prodquan = 0;
                   num1= JOptionPane.showInputDialog( "Enter Product Number, -1 to Quit");
                   prodnum = Integer.parseInt(num1);
              while (prodnum != -1) {
              switch ( prodnum ) {
                   case 1:
                        JOptionPane.showMessageDialog(null, "1 - $2.98");
                        break;
                   case 2:
                        JOptionPane.showMessageDialog(null, "2 - $4.50");
                        break;
                   case 3:
                        JOptionPane.showMessageDialog(null, "3 - $9.98");
                        break;
                   case 4:
                        JOptionPane.showMessageDialog(null, "4 - $4.49");     
                        break;
                   case 5:
                        JOptionPane.showMessageDialog(null, "5 - $6.87");     
                        break;
                   default:
                        JOptionPane.showMessageDialog(null, "Invalid value entered" );     
                        break;
                   }//end switch
                   num2= JOptionPane.showInputDialog( "Enter Quantity, -1 to Quit");
                   quant = Integer.parseInt(num2);
                   num1= JOptionPane.showInputDialog( "Enter Product Number, -1 to Quit");
                   prodnum = Integer.parseInt(num1);
                   if (prodnum == 1) {
                        input = quant * 239;
                   else if (prodnum == 2) {
                        input = quant * 129;     
                   else if (prodnum == 3) {
                        input = quant * 99;
                   else if (prodnum == 4) {
                        input = quant * 350;
                   else if (prodnum == 5) {
                        input = quant * 350;
                   }//endif
                   gtotal = input + 0;
                   Counter = Counter + 1;
              } //end while
              DecimalFormat twoDigits = new DecimalFormat( "0.00");
              if ( Counter != 0) {
              //     average = (double) total/ Counter;
                   lahatna = lahatna + gtotal;
                   JOptionPane.showMessageDialog(null, "Retail Total " + twoDigits.format( lahatna ),
                   "Mail Order House",JOptionPane.INFORMATION_MESSAGE );
              else
              JOptionPane.showMessageDialog( null,"No Product number entered", " ",JOptionPane.INFORMATION_MESSAGE );
              System.exit( 0 );

    Hi.
    I hope the class below meets your needs. Please note that I didn't spend too much time testing it and that I cannot guarantee that it works perfectly. At least it should calculate the correct results for the input values.
    public class ProbMod {
        public ProbMod() {
        public static void main(String[] args) {
            int productNumber = 0;
            int soldAmount = 0;
            double price = 0.0;
            int counter = 0;
            double total = 0.0;
            do {
                try {
                    productNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter product number (-1 to quit)"));
                    switch( productNumber ) {
                        case -1:
                            break;
                        case 1:
                            price = 2.98;
                            break;
                        case 2:
                            price = 4.5;
                            break;
                        case 3:
                            price = 9.98;
                            break;
                        case 4:
                            price = 4.49;
                            break;
                        case 5:
                            price = 6.87;
                            break;
                        default:
                            JOptionPane.showMessageDialog(null, "You have entered an invalid product number. Please try again.");
                            throw new Exception("");
                    if( productNumber != -1 ) {
                        soldAmount = Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
                        total += (double)soldAmount * price;
                        counter++;
                } catch( NumberFormatException e1 ) {
                    JOptionPane.showMessageDialog(null, "You have entered a non numeric value. Please try again.");
                    productNumber = 0;
                } catch( Exception e2 ) {
                    productNumber = 0;
            } while( productNumber != -1 );
            JOptionPane.showMessageDialog(null, "Retail total (" + String.valueOf(counter) + " product(s)): " + new DecimalFormat("0.00").format(total));
    }Regards,
    Kai

  • Problem with String in JSP! Help Me

    Hi all,
    i spent my whole day with this error. How can i solve it. I am trying to convert a string array to Integer array. The program is taking all the select input from the previous JSP page and then converting them into integer array for storing to database. i am catching them as request.getParameterValues(); but i found out that if i select 4 item from the menu it is storing in 8 array cells and the format is if you select 1 2 3 4 the it stores [1 null 2 null 3 null 4 null] i guessed that those are null values. so i have tried to select only 1 2 3 4 from the array and it is showing number format error on tomcat. here is the code guys. Please i am tired of it please help me. Thanks. SORRY I TRIED TO SEPARATE THE CODE BUT IT SEEMS LIKE THERE ARE SOME PROBLEM IN THE FORUM SETTINGS. so the code is:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@page import="java.io.*"%>
    <%@page import="java.sql.*"%>
    <%@page import="java.lang.String.*"%>
    <%@page import="java.lang.Character.*"%>
    <%@page import="java.util.*"%>
    <%@page import="java.text.*"%>
    <HTML>
    <HEAD>
    <TITLE> HR ADVANTAGE TIMESHEET </TITLE>
    </HEAD>
    <BODY>
    <%
    String emplno = request.getParameter("emplno");
    String date = request.getParameter("date");
    String proposal = request.getParameter("proposals");
    String network1 = request.getParameter("network");
    String suppassociates = request.getParameter("suppasso");
    String intmngt = request.getParameter("intmgt");
    String client[] = request.getParameterValues("client");
    String client1= request.getParameter("client1");
    String clientunit[] = request.getParameterValues("clientunit");
    String clientunit1=request.getParameter("clientunit1");
    boolean bool=true;
    int staffid = Integer.parseInt(emplno);
    int len=0;
    len=client.length;
    //String[] check_client = new String[len];
    //check_client=client;
    //int check_length=0;
    //check_length=check_client.length;
    //int unitlength=0;
    //unitlength=clientunit.length;
    int arr_length=0;
    arr_length=len-(len/2);
    int[] array = new int[arr_length];
    int j=0;
    j=arr_length;
    for (int i=0; i<len-1; i++)
    bool=true;
    if(client=="\0")
    bool=false;
         if(bool==true)
         array[arr_length-j]=Integer.parseInt(client[i]);
              j=j-1;
              if(j==0)
              break;
    %>
    </BODY>
    </HTML>
    The error is:
    org.apache.jasper.JasperException: For input string: ""
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:367)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:293)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:240)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.lang.NumberFormatException: For input string: ""
         java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
         java.lang.Integer.parseInt(Integer.java:489)
         java.lang.Integer.parseInt(Integer.java:518)
         org.apache.jsp.store_jsp._jspService(store_jsp.java:107)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:136)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:320)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:293)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:240)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

    what are you trying to test with client [ i ] == "\0"
    You sure you dont need to test against null ?

Maybe you are looking for

  • ACD 30" Dual Link DVI and MacBook Pro Unibody

    I have the following configuration: ACD 30" Dual Link DVI and MacBook Pro Unibody I am exhibiting some intermittent problems with the 30" display not coming up when I reboot for example and here are some more: 1. MacBook Pro not in clam-shell mode an

  • File share with MINIMUM CPU use

    Going to be connecting two G4's over a 100-T router. What is the least CPU intensive way to trasnfer files on computer A to computer B? FTP? Personal File Sharing? I need the least CPU intensive out of all the possible options available. Burning not

  • Report Script output in UTF-8 code with Non-Unicode Application

    Essbase Nation, Report Script output (.txt) file is being coded as UTF-8 when the application is set to Non-unicode. This coding creates a signature character in the first line of the text file, which in turn shows up when we import the file into Mic

  • Field symbols?

    Hi, Can any one give me clear idea of field symbols and their use in the programing? i read some help docs but could not get it what exactly it means Thanks, Ravi

  • Feels like I am using a beta version of PE 10

    I am using PE10 since about one year but I am not completely satisfied with the software. There are so many bugs in it... -     When starting PE10 on my Dual Core 3.0 GHz PE10 will stay at a 100% CPU usage, even when there is no project loaded. I kno