Forwarding the array of object to servlet class

Hi
i am new to this j2ee.So please cooperate with me.
i am having an array of objects in a jsp page.
Each object represent a option which could be seelected through radio button.
Now i want to send one selected object,corresponding to selected radio button to my servlet ManageUser.
how can i do that.can any one help me please.
i have been trying like this but i guess it is not correct .
<%--   
--%>   
<%@page contentType="text/html" pageEncoding="UTF-8"%>    
<%@page import="abc.javabean.EmpJavaBean"%>  
<!--importing pages(classes) to implement request response  -->  
<%@page import="javax.servlet.ServletException"%>  
<%@page import="javax.servlet.http.HttpServlet"%>  
<%@page import="javax.servlet.http.*"%>  
<%@page import="javax.servlet.RequestDispatcher"%>  
<%@page import="java.util.*"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd">    
<html>  
    <head>  
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
        <title>JSP Page</title>  
        <script type="text/javascript">  
            //function for selecting the radio  
            function validateRadio(fetchedArrayObject)  
                alert("hi");  
                var thisone=-1;  
                for(i=0;i<document.searchedEmpForm.radioGroup.length;i++)  
                        if(searchedEmpForm.radioGroup.checked==true)
thisone=i;
alert(thisone);
var name=fetchedArrayObject[i].getEmpName();
alert(name);
session.setAttribute("fetchedArrayObject[i]",fetchedArrayObject[i]);
if(thisone==-1)
alert("you must select a radio Button");
return false;
return true;
</script>
</head>
<body bgcolor="#8db6cd">
<!--retreaving the array values from the servlet -->
<%
//int a;
EmpJavaBean fetchedArrayObject[]=new EmpJavaBean[4];
fetchedArrayObject=(EmpJavaBean[])request.getAttribute("substituteArray");
//a=fetchedArrayObject[0].getEmpNumber();
%>
<h3>ur new no is <%=fetchedArrayObject[0].getEmpNumber()%></h3><br>
<form name="searchedEmpForm" action="/Precize/ManageUser" onsubmit="return validateRadio(fetchedArrayObject)">
<br></br>
<h2 align="center">Your Searched Result Is Here</h2>
<br></br>
<table border="1" align="center">
<thead>
<tr>
<th> </th>
<th> <input type="button" value="Emp#" name="searchedPageEmpNumb"> </th>
<th> <input type="button" value="Name" name="searchedPageEmpName"> </th>
<th> <input type="button" value="Priv" name="searchedPageEmpPriv"> </th>
<th> <input type="button" value="Role" name="searchedPageEmpRole"> </th>
<th> <input type="button" value="Start Date" name="searchedPageEmpStartDate"> </th>
<th> <input type="button" value="End Date" name="searchedPageEmpEndDate"> </th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" name="radioGroup" value="r11" ></td>
<td><%=fetchedArrayObject[0].getEmpNumber()%></td>
<td><%=fetchedArrayObject[0].getEmpName()%></td>
<td><%=fetchedArrayObject[0].getEmpPrivilege() %></td>
<td><%=fetchedArrayObject[0].getEmpRole()%></td>
<td><%=fetchedArrayObject[0].getEmpStartdate()%></td>
<td><%=fetchedArrayObject[0].getEmpEndDate() %></td>
</tr>
</tbody>
</table>
<br><center><input type="submit" value="Update" name="updateButton" ></center>
<h3 align="center">Select the Employee To be Updated/deleted</h3>
</form>
</body>
</html>
please suggest me the answer.
regards
thanx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

I think you need to learn the difference between "java" and "javascript"
calling session.setAttribute from a javascript function will not have the effect that you desire.
If you give all radio buttons the same "name", then request.getParameter("radioGroup") should tell you the value of the selected one.

Similar Messages

  • Creating an arrays of objects from a class

    I was wondering does any one know how to create an array of objects from a class?
    I am trying to create an array of objects of a class.
    class name ---> Class objectArray[100] = new Class;
    I cant seem to make a single class but i need to figure out how to create an array of objects.
    I can make a normal class with Class object = new Class

    There are four lines of code in your for-loop that actually do something:
    for(index = 0; index < rooms.length; index++) {
    /*1*/  assignWidth.setWidth(Double.parseDouble(in.readLine()));
    /*2*/  rooms[index] = assignWidth;
    /*3*/  assignLength.setWidth(Double.parseDouble(in.readLine());
    /*4*/  rooms[index] = assignLength;
    }1.) Sets the width of an object, that has been instantiated outside the loop.
    2.) assigns that object to the current position in the array
    3.) Sets the width of a second object that has been instantiated outside the loop
    4.) assigns that other object to the current position in the array
    btw.: I bet you meant "assignLength.setLength(Double.parseDouble(in.readLine());" in line 3 ;)
    Since each position in an array can only hold one value, the first assignment (line 2) is overwritten by the second assignment (line 4)
    When I said "construct a new room-object and assign it to rooms[index]" I meant something like this:
    for(index = 0; index < rooms.length; index++) {
        Room aNewRoom = new Room();
        aNewRoom.setWidth(Double.parseDouble(in.readLine()));
        aNewRoom.setLength(Double.parseDouble(in.readLine());
        rooms[index] = aNewRoom;
    }1.) Constructs a new Object in every iteration of the for-loop. (btw: I don't know what kind of objects you're using, so this needs most likely modification!!)
    2.) set the width of the newly created object
    3.) set the length of the newly created object
    4.) assign the newly created object to the current position in the array
    -T-
    btw. this would do the same:
    for(index = 0; index < rooms.length; index++) {
        rooms[index] = new Room();
        rooms[index].setWidth(Double.parseDouble(in.readLine()));
        rooms[index].setLength(Double.parseDouble(in.readLine());
    }but be sure you understand it. Your teacher most likely wants you to explain it ;)

  • Creating an array of objects of a class known ONLY at RUNTIME

    I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
    Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
    Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
    Thanks a lot in advance.

    Sorry, for the small typo. It is -
    clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
    instead
    Thanks for the reply. I could do this. But I am
    getting a handle to the method to be 'invoke'd by
    looking at the types of the parameters its
    expecting(getParameterTypes). So I can't change it to
    accept an array of Generic Objects.
    I looked at the java.lang.reflect.Array class to do
    this. This is what I am trying to do-
    String variableName is an input coming into my
    program.
    n is the size of the array I'm trying to create.
    Class clazz = Class.forName(variableName);
    clazz[] arr = (clazz
    [])java.lang.reflect.newInstance(clazz, n);
    According to Reflection API, it should work, right?
    But compiler yells at me saying 'class clazz not
    found'.
    Any suggestions/hints/help?
    Thanks, again.

  • Java sorting the array of objects

    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :
    public classmyObj extends Nullable
        private int objId;
        private Datemydate;
        public int getObjID();
        public Date getmyDate();
        public int getISecondD();
      }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?
    Please help with this!
    Thanks

    neeto wrote:
    Hi ,
    I have a question on sorting objects in java.
    I have a java interface some thing like :You mean class?
    >
    public classmyObj extends Nullable
    private int objId;
    private Datemydate;
    public int getObjID();
    public Date getmyDate();
    public int getISecondD();
    }I need to create the array of the objects of this class that are sorted on the ObjID:
    classmyObj[] collectionObjects
    I need to pass this collectionObjects to another function.
    Now how should I sort these objects based on the ObjID on collection?Create a comparator and use it in a call to Collections.sort (or Arrays.sort if you have an array)

  • How to initialize the array with object?

    Here is type I have.
    CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_TYPE AS OBJECT
    BU_AP VARCHAR2(5),
    VOUCHER VARCHAR2(10),
    V_LINE INTEGER,
    USERID VARCHAR2(20),
    COMMENT_DTTM DATE,
    COMMENT VARCHAR2(254)
    CREATE OR REPLACE TYPE SYSADM.AP_COMMENT_COLL AS VARRAY(1000) OF SYSADM.AP_COMMENT_TYPE;
    Then I created a procedure to grab some data.
    PROCEDURE get_voucher_comments (
    v_bu_in IN VARCHAR2,
    v_voucher_in IN VARCHAR2,
    v_line_in IN NUMBER,
    v_userid IN VARCHAR2,
    voucher_comment OUT      sysadm.ap_comment_coll
    IS
    i NUMBER := 1;
    v_comments VARCHAR2 (254) := ' ';
    comment_type sysadm.ap_comment_type;
    v_line_num NUMBER := 0;
    CURSOR get_all_comment
    IS
    SELECT voucher_line_num, descr254_mixed
    FROM ps_fas_ap_comment
    WHERE business_unit = voucher_comment (i).bu_ap
    AND voucher_id = voucher_comment (i).voucher;
    CURSOR get_line_comment
    IS
    SELECT descr254_mixed
    FROM ps_fas_ap_comment
    WHERE business_unit = voucher_comment (i).bu_ap
    AND voucher_id = voucher_comment (i).voucher
    AND voucher_line_num = voucher_comment (i).v_line;
    BEGIN
    voucher_comment (1) := ap_comment_type (' ', ' ', 0, ' ', '', ' ');
    --voucher_comment (1) := ap_comment_type (null, null, null, null, null,null);
    IF voucher_comment (i).v_line = 0
    THEN
    OPEN get_all_comment;
    LOOP
    FETCH get_all_comment
    INTO v_line_num, v_comments;
              voucher_comment.EXTEND;
    voucher_comment (i) :=
    ap_comment_type (v_bu_in,
    v_voucher_in,
    v_line_num,
    v_userid,
    TO_DATE (TO_CHAR (SYSDATE,
    'DD-MON-YYYY HH24:MI:SS'
    'DD-MON-YYYY HH24:MI:SS'
    v_comments
    i := i + 1;
    END LOOP;
    ELSE
    OPEN get_line_comment;
    LOOP
    FETCH get_line_comment
    INTO v_comments;
              voucher_comment.EXTEND;
    voucher_comment (i) :=
    ap_comment_type (v_bu_in,
    v_voucher_in,
    v_line_num,
    v_userid,
    TO_DATE (TO_CHAR (SYSDATE,
    'DD-MON-YYYY HH24:MI:SS'
    'DD-MON-YYYY HH24:MI:SS'
    v_comments
    i := i + 1;
    END LOOP;
    END IF;
    END get_voucher_comments;
    But when I tried to test the procedure, got error: ORA-06531: Reference to uninitialized collection. Does anyone have experience of handling array with object?
    declare
    O_voucher_comment SYSADM.AP_COMMENT_COLL;
    begin
    FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 1, 'KEHE', O_voucher_comment);
    end;

    Thanks for that. I changed it a little bit, but when i ran this script, got ORA-06532: Subscript outside of limit.
    declare
    O_voucher_comment SYSADM.AP_COMMENT_COLL := sysadm.ap_comment_coll(null);
    begin
    FAS_AP_EXCEPTIONS.GET_VOUCHER_COMMENTS('FCCAN', '20494753', 0, 'KEHE', O_voucher_comment);
    end;
    PROCEDURE get_voucher_comments (
    v_bu_in IN VARCHAR2,
    v_voucher_in IN VARCHAR2,
    v_line_in IN NUMBER,
    v_userid IN VARCHAR2,
    voucher_comment OUT      sysadm.ap_comment_coll
    IS
    i NUMBER := 1;
    v_comments VARCHAR2 (254) := ' ';
    comment_type sysadm.ap_comment_type;
    v_line_num NUMBER := 0;
    CURSOR get_all_comment
    IS
    SELECT voucher_line_num, descr254_mixed FROM ps_fas_ap_comment
    WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in;
    CURSOR get_line_comment
    IS
    SELECT descr254_mixed FROM ps_fas_ap_comment
    WHERE business_unit = v_bu_in AND voucher_id = v_voucher_in
    AND voucher_line_num = v_line_in;
    BEGIN
    --voucher_comment() := SYSADM.ap_comment_type (NULL, NULL, NULL, NULL, NULL, NULL);
    --' ', ' ', 0, ' ', '', ' ' sysadm.ap_comment_coll
    voucher_comment := sysadm.ap_comment_coll(null);
    IF v_line_in = 0
    THEN
    OPEN get_all_comment;
    LOOP
    FETCH get_all_comment
    INTO v_line_num, v_comments;
              if i > 1
              then
                   voucher_comment.EXTEND;
              end if;
    voucher_comment (i) := ap_comment_type (v_bu_in,
    v_voucher_in, v_line_num, v_userid,
    TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS'), 'DD-MON-YYYY HH24:MI:SS'), v_comments );
    i := i + 1;
    END LOOP;
    ELSE
    OPEN get_line_comment;
    LOOP
    FETCH get_line_comment
    INTO v_comments;
              voucher_comment.extend(6);
    voucher_comment (i) := ap_comment_type (v_bu_in, v_voucher_in, v_line_num, v_userid, TO_DATE (TO_CHAR (SYSDATE, 'DD-MON-YYYY HH24:MI:SS' ), 'DD-MON-YYYY HH24:MI:SS'), v_comments);
    i := i + 1;
    END LOOP;
    END IF;
    END get_voucher_comments;

  • How to retrict the number of object that a class can have...

    hi
    i m just writing a banking program and each customer can only have
    2 accounts,,,so i need to restrict the number of account object that a customer
    can have,,
    so i need to count object? or something like that so that when a customer
    try to create more account, i need to stop them. but
    i don't know how to do that....
    customer can only have two accounts, and,,,,how do i know
    if customer already have two accounts...........................

    i m just writing a banking program and each customer
    can only havePlease make the extra effort to write out words such as "am". The extra keystrokes won't cost much in the way of time, and the enhanced clarity will be appreciated by those communicating on a forum with international readership.
    >
    so i need to count object? Yes. The customer can possess a reference to each account. If the customer has two accounts, the customer can register no more.
    i don't know how to do that....
    The Java� Tutorial - A practical guide for programmers
    customer can only have two accounts, and,,,,how do i
    knowBy counting the number of accounts a customer has!
    P.S. What's with the repeated punctuation?

  • Displaying the contents of an array of objects

    Hello All,
    My Java teacher gave us a challenge and I'm stumped. The teacher wants us to display the contents of the array in the main menthod. The original code is as follows:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    }I understand that the elements of the array are objects, and each one has a value assigned to it. The following code was my first attempt at a solution:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
                                    for ( int i = 0; i < thingArray.length; i++)
                                       System.out.println( thingArray );                         
    }To which I'm given what amounts to garbage output. I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array. There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. Thanks very much in advance!

    robrom78 wrote:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    for ( int i = 0; i < thingArray.length; i++)
    System.out.println( thingArray );                         
    Note that you're trying to print the entire array at every loop iteration. That's probably not what you meant to do.
    You probably meant to do something more like
                                 System.out.println( thingArray[i] );Also, note that the java.util.Arrays class has a toString method that might be useful.
    To which I'm given what amounts to garbage output. It's not garbage. It's the default output to toString() for arrays, which is in fact the toString() defined for java.lang.Object (and inherited by arrays).
    I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array.It displays a default result that is vaguely related to the memory, but probably shouldn't be thought of us such. Think of it as identifying the type of object, and a value that differentiates it from other objects of the same type.
    By the way I assume you mean "+not+ the contents of the array" above. If so, that is correct.
    There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? No, you don't override a method in println; actually methods don't contain other methods directly. You probably do need to override toString in Thing.
    I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. You can get to the individual objects in the array just by dereferencing it, as I showed you above.
    But I suspect that won't be sufficient. Most likely, Thing doesn't have a toString method defined. This means that you'll end up with very similar output, but it will say "Thing" instead of "[Thing" and the numbers to the right of the "@" will be different.
    You'll need to override the toString() method in Thing to get the output you want.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • How can I find the real path to servlet class

    Hi,
    I am facing an issue. Am in the process of creating a filter which would send a Last-modified along with the header. For this I will be checking the is-modified-since
    header and lastModified date of the file.
    The problem I am facing is that after taking the file part from the request and checking
    the lastmodified date, it gives error. This is because i use,
    String real_path = getServletContext().getRealPath(request.getServletPath());
    and it would return the path to servlet-name and not to servlet-class, since servlet-name
    is not physically present. It would return an error value.
    Is there any way which I could find the real path to my servlet class file ?

    Remember you should not take the last mnodified date
    of the class file or the jar file that contain the
    class as the value for the getLastModified method
    becouse the last modified date that should be used in
    the caching is the last modified date of the dynamic
    content that the servlet is about to prodice.
    The same class file will produce different content
    for different requests if not why do you use
    servlets you can directly use the static contentThanks for a valuable remark.
    Hence our getLastModified() often returns System.currentTimeMillis() result.

  • Passing an array of objects to a method.

    Hi I'm building a program to act as a CD Collection Database. An array of objects represents the entries: Artist, Album and NUmber of Tracks. What I want to do is in the Menu, user to choose wether he or she wants to Add new CD to collection, print or quit, if he/she does then I call a method addNewEntry, to which i pass the array of objects called array, and I want the user to enter the entries each in turn, after that i want the program to return to the method Menu and ask if he or she wants to quit, print or add new cd. The idea is that the details entered already would be contained in the array of objects [0], so the next set of details go to [1] and then to [2] and so on. I have build up the code at this stage but i get an error while copmiling and im totally stuck. Im a beginner in Java.
    Here is the code:
    //by Andrei Souchinski
    //Mini Project: CD Collection Database
    //Designed for a grade F
    //Defining new class of objects to represent CD database entries.
    //A database entry consists of the artist name, the album name and number of tracks.
    //A single entry can be entered by the user typing the details in and the entry can be printed out.
    import javax.swing.*;
    import java.util.*;
    public class MiniProject
         public static void main (String[] args)     
              System.out.println("\tCD Collection Database\n");
              System.out.println("1. Add new Compact Disk to the Database");
              System.out.println("2. Print out current database entries");
              System.out.println("3. Quit\n");          
              theMenu();
         public static void theMenu()
              CompactDisk [] array = new CompactDisk[20];
              String menu;
              menu = JOptionPane.showInputDialog("What would you like to do?");
              if (menu.equals ("3"))
                   JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
                   System.exit(0);     
              if (menu.equals ("2"))
              if (menu.equals ("1"))
              addNewEntry(array);
              else
                   JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
                   theMenu();
         public int addNewEntry(int newcd[])
                   int i;          
                   newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
                   newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Album"));
                   newcd[i] = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
    //A Compact Disk entry consists of three attributes: artist name, album and number of tracks
    class CompactDisk
         public String artistname; //Instance variables for artistname, albumname and numberoftracks.
         public String albumname;
         public int numberoftracks;
         public CompactDisk(String n, String a, int t)
         artistname = n; //Stores the 1st argument passed after "new Dates" into day
         albumname = a; //Stores the 2nd argument passed after "new Dates" into month
         numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
         //When called from the main method, prints the contents of
         //artistname, albumname and numberoftracks on to the screen.
         public void printCompactDisk ()
                   String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
                   System.out.println(output);
    }

    //by Andrei Souchinski
    //Mini Project: CD Collection Database
    //Designed for a grade F
    //Defining new class of objects to represent CD database entries.
    //A database entry consists of the artist name, the album name and number of tracks.
    //A single entry can be entered by the user typing the details in and the entry can be printed out.
    import javax.swing.*;
    import java.util.*;
    public class MiniProject
         public static void main (String[] args)     
              System.out.println("\tCD Collection Database\n");
              System.out.println("1. Add new Compact Disk to the Database");
              System.out.println("2. Print out current database entries");
              System.out.println("3. Quit\n");          
                theMenu();
         public static void theMenu()
              String menu;
              menu = JOptionPane.showInputDialog("What would you like to do?");
              if (menu.equals ("3"))
                   JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
                   System.exit(0);     
              if (menu.equals ("2"))
              if (menu.equals ("1"))
              addNewEntry();
              else
                   JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
                   theMenu();
         public static void addNewEntry()
                   CompactDisk [] array = new CompactDisk[20];
                   int i = 0;
                   array.artistname = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
                   array[i].albumname = (JOptionPane.showInputDialog("Please enter the name of the Album"));
                   array[i].numberoftracks = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
    //A Compact Disk entry consists of three attributes: artist name, album and number of tracks
    class CompactDisk
         public String artistname; //Instance variables for artistname, albumname and numberoftracks.
         public String albumname;
         public int numberoftracks;
         public CompactDisk(String n, String a, int t)
         artistname = n; //Stores the 1st argument passed after "new Dates" into day
         albumname = a; //Stores the 2nd argument passed after "new Dates" into month
         numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
         //When called from the main method, prints the contents of
         //artistname, albumname and numberoftracks on to the screen.
         public void printCompactDisk ()
                   String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
                   System.out.println(output);
    I've edited the code, itcompiles, but gives an error when i ran it..:(

  • Determining which method to call from an array of Objects

    Hi All,
    Lets suppose I have an interface, a string method name, and an array of Objects indicating the parameters which should be passed to the method.
    What Im trying to work out is a way to quickly determine which method should be invoked.
    I can see that Class has getDeclaredMethod(String, Class[]), but that wont help me as I dont know the formal class types (the method may take X, but I might get passed Y which extends X in the array of objects).
    Does anyone know of a quick way I can determine this?
    All I can think of at the moment is going thru each method of the class one by one, and seeing if the arg is assignable, then, after getting all my matched methods, determining if there are any more 'specific' matches.
    Any ideas?
    Much appreciated,
    Dave

    you might want to take a look at the dynamic proxy apiCheers for the suggestion, but Im actually already using the dynamic proxy API.
    What I have is a MockObjectValidator which allows mock objects to be configuered with expected calls, exceptions to throw etc etc.
    I thought developers on my project would get tired using an interface like this:
    myValidator.setExpectedCall("someMethod", new Class[] { typeA, typeB }, new Object[] { valueA, valueB} );
    I.e, I wanted to cut out having to pass the class array, so they could just use:
    myValidator.setExpectedCall("someMethod", new Object[] { valueA, valueB} );
    The problem there is that I then need to pick the best Method from the class given the object arguments.
    When the mock object is in use, its no problem as the InvocationHandler interface provides the Method. The problem I have is selecting what method a user is talking about from an array of Objects.
    Ive written a simple one now, it just does primitive type class -> wrapper substitution, and then finds ** A ** match. If there is more than one match (ie, all params are assignable to a class' method params), I dont let that method be used.
    Shortly I'll update it to actually make the correct selection in those cases.
    cheers
    Dave

  • An array of objects

    Hi,
    I'm having trouble creating an array of objects to store data I'm reading in from a text file.
    I have created a class called mssg, and as I read each line of the textfile in, I've created a method called setMsg that I'm using to populate the mssg object I've created.
    This works fine when I use this method on a single instance of a mssg object, but when I try to use the same code on a mssg object that's part of an array, I get an exception (and one that doesn't have any friendly error text)
    mssg ms = new mssg();  //this works as expected
    mssg msgs[] = new mssg [msgCounter]; //I believe the exception relates to how I'm declaring the array of objects here, but the exception doesn't occur until I try to assign data to an element of the arrayThe lines below are where the problem becomes apparent. The first object 'ms' gets assigned its values as I'd expect, however, the line below that tries to assign values to a mssg object in the msgs array, and I get an exception immediately.
    ms.setMsg(currMsg,mDt,mTm,mDir,mData);
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);Can anyone tell me what I'm doing wrong in terms of declaring/assigning values to an array of objects?

    It's the following error: java.lang.NullPointerException
    Full error text if I take my code out of a try/catch loop is:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at FIXparserUI.jMenuLoadActionPerformed(FIXparserUI.java:301)
            at FIXparserUI.access$100(FIXparserUI.java:20)
            at FIXparserUI$3.actionPerformed(FIXparserUI.java:129)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
            at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1170)
            at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1211)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)at the point that the following line of code is run:
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);msgCounter is used to count the number of lines in the file (about 2300)
    I had hoped that what I was doing with this line:
    mssg msgs[] = new mssg [msgCounter];was create 2300 empty mssg records, ready to be populated from each line of data, however I have the feeling you're going to tell me I'm wrong.

  • Formatted .data file, reading in and creating an array of objects from data

    Hi there, I have written a text file with the following format;
    List of random personal data: length 100
    1 : Atg : Age 27 : Income 70000
    2 : Dho : Age 57 : Income 110000
    3 : Lid : Age 40 : Income 460000
    4 : Wgeecnce : Age 43 : Income 370000
    and so on.
    These three pieces of data, Name,Age and Income were all generated randomly to be stored in an array of objects of class Person.
    Now what I must do is , read in this very file and re-create the array of objects that they were initially written from.
    I'm totally lost on how to go about doing this, I have only been learning java for the last month so anyone that can lend me a hand, that would be superb!
    Cheers!

    Looking at you other thread, you are able to create the code needed - so what's the problem?
    Here's an (not the only) approach:
    Create an array of the necessary length to hold the 3 variables, or, if you don't know the length of the file, create a class to contain the data. Then create an ArrayList to hold an instance of the class..
    Use the Scanner class to read and parse the file contents into the appropriate variables.
    Add each variable to either the array, or to an instance of the class and add that instance to the arraylist.

  • Accessing data in an array of objects..

    I've created the classes
    public class Box
    int width;
    int height;
    int depth;
         public Box(int a, int b, int c)
         width = a;
         height = b;
         depth = c;
         public void getWidth()
         System.out.println(width);
         public void getHeight()
         System.out.println(height);
         public void getDepth()
         System.out.println(depth);
    }and this collection of boxes...
    public class Collecton
         int count = 0;
         Box[] BoxCollection;
         public Collection
         BoxCollection = new Box[50]
         public recbox(int a, int b, int c)
         BoxCollection[count] = new Box(a, b, c)
         count++
         public printBoxes()
         System.out.println("Box Number = " + count);
         System.out.print("Box Width: ");
         BoxCollection[count].getWidth();
         etc...
    }Now, I call this in the main code so that after each box is created, the specs of the box is printed back out onto the screen. The calling procedure works
    However, only the Box Number part seems to print... the width, height and depth all don't work.
    Am I accessing the data stored in the array of objects incorrectly?
    Please advise.
    Thanks

    a b and c come from user inputs via an input/output lib... and you are sure this user input works? Perhaps you're searching in the wrong place: Do a System.out.println(a + ", " + b + ", " + c) just after getting that user input (from console?) and check the values.
    Patrick

  • Plz help!! array of object (for search)

    i've got few questions of array of object
    1-how to search for a price that is greater than 300 in the array of object
    and how to list all of them?
    2- how to search for the smallest price in the array of object, and how to list?
    can anyone provde a java code for me:P?
    but plz don't too complex
    coz i'm a learner of javaT_T

    _< i still can't understand, and dunno how to change into the code that i needand you guyz help me change it?
    /*wirte the driver program which will define and create an array of
    objects instantiated from the class WaterBill
    Create Accessor and Mutator methods to get/set data from the class.
    write code within the driver method to perfrom the following:
    a) The final total of funds
    b) To search for accounts greater than $300 in the array of objects,
         and list all the customer details
    c)To search for the lowest bill in the array of objects, and list
    those customer dtails
    Class definitions and Objects  using price
    import java.text.*;
    import javax.swing.JOptionPane;
    public class Pre_pb3
         public static void main(String []args)
              int  TTc=0;
              int accNum[]=new int[20];
              String name[]=new String[20], output, stans, display; //stAccNum, stUsage, stTTc;
              double usage[]=new double[20];
              double TTa=0.0;
              double price[]=new double[20];
              char ans;
              double acctG,lowest;
              int i=0;
              waterBill MYwaterBill = new waterBill();
              ans='Y';
              while (!(ans=='N'))
                   name=inputName();
                   accNum[i]=inputAccNum();
                   usage[i]=inputUsage();
                   price[i]=calculateAmountOwing(usage[i]);
                   TTa=MYwaterBill.TTaPrice(price[i]);
                   output=MYwaterBill.outputInfo(name[i], accNum[i], usage[i], price[i]);
                   waterBill MYwaterBill2= new waterBill(name[i], accNum[i],usage[i], price[i]);     
                   stans=JOptionPane.showInputDialog("Do you wanna continue?, (Y)es, (N)o");
                   stans = stans.substring(0, 1);
                   stans=stans.toUpperCase();
                   ans=stans.charAt(0);
                   TTc++;     
              MYwaterBill.outputoutput(TTc, TTa);
              MYwaterBill.findGreat();     //b)
              MYwaterBill.searchDetail();     //c)
              System.exit(0);                                                  
         public static String inputName()
                   String name;
                   name=JOptionPane.showInputDialog("Enter Name ");
                   return name;
         public static int inputAccNum()
              int accNum;
              String stAccNum;
              stAccNum=JOptionPane.showInputDialog("Enter Account Number");
              accNum=Integer.parseInt(stAccNum);
              return accNum;
         public static double inputUsage()
              double usage;
              String stUsage;
              stUsage=JOptionPane.showInputDialog("Enter Water Usage");
              usage=Double.parseDouble(stUsage);
              if (!(usage>=0 && usage<=99999999))
                   System.out.println("water useage is invalid");
                   System.exit(0);
              return usage;
         public static double calculateAmountOwing(double usage)
              double price=0.0;
              if (usage>=0)
                   if (usage<=10000)
                        price=(10000/10)*0.01;
                   else if (usage>10000)
                        price=((10000/10)*0.01)+(((usage-10000)/10)*0.02);
              else
                        System.out.println("Error of usage");
                   return price;
    class waterBill
         private static     int TTc=0 ,accNum=0;
         private static String name, stAccNum, stUsage, stTTc;
         private static String output=" ";
         private static double usage=0.0;
         private static double TTa=0.0;
         private static double price=0.0;
         private static String lowest;
         public waterBill()
              name=" ";
              accNum=0;
              usage=0.0;
              price=0.0;
         public waterBill(String n,int an, double us, double p)
              setName(n);
              setAccNum(an);
              setUsage(us);
              setPrice(p);
         public void setName(String n)
              name=n;
         public void setAccNum(int an)
              accNum=an;
         public void setUsage(double us)
              usage=us;
         public void setPrice(double p)
              price=p;
         public String getName()
              return name;
         public int getAccNum()
              return accNum;
         public double getUsage()
              return usage;
         public double getPrice()
              return price;
         public double TTaPrice(double price)
              TTa=TTa + price;
              return TTa;
         public String outputInfo(String name, int accNum, double usage, double price )
              String output=" ";                         
              output: System.out.println( "Account Number: "+ accNum +
                                       "\nWater Usage: " + usage +
                                       "\nCost Owing: " price
                                       "\nName: "+ name+"\n");
              return output;
         public void outputoutput(int TTc, double TTa)
              display:     System.out.println("Total customer: "+ TTc +
                                  "\nTotal amount owing: " + TTa + "\n\n");
         public void findGreat()//search the a/c that is greater than 300.
              //dunno how to do, so i just leave it blank^^"
              public String searchDetail()//search the smallest a/c
              //same...dunno how to doT_T     

Maybe you are looking for