Passing a class as an argument

Hi!
Is it possible in Java to pass the reference to a class (not an instance of a class) as an argument to a method? More specifically, I would like a method that can take the reference to a class Y implementing Interface X. The method would then be able to call static and nonstatic methods of Y (including a constructor), which are implementations of methods in X. Is such a thing possible? Or would I do it differently?
My actual case is a scanner, which is supposed to scan a stream and divide it into tokens. It would like to pass different implementations of my interface Token (AToken, BToken, ...) for scanning streams of different kinds. That way I would write the scanner only once and would only have to come up with a new implementation of Token whenever I want to scan a new kind of Stream.
Thanks for help,
Dunk

My actual case is a scanner, which is supposed to scan
a stream and divide it into tokens. It would like to
pass different implementations of my interface Token
(AToken, BToken, ...) for scanning streams of
different kinds. That way I would write the scanner
only once and would only have to come up with a new
implementation of Token whenever I want to scan a new
kind of Stream.There does not seem to be anything in the description of your problem that forces the use of Reflection. You can use an Interface as the argument of a method so the method does not need to know the actual type of the object instance. Similarly, you might use an abstract class.

Similar Messages

  • Passing Wrapper Classes as arguments

    I have a main class with an Integer object within it as an instance variable. I create a new task that has the Integer object reference passed to it as an argument, the task then increases this objects value by 1. However the objects value never increases apart from within the constructor for the task class, it's as if it's treating the object as a local variable. Why?
    mport java.util.concurrent.*;
    public class Thousand {
         Integer sum = 0;
         public Thousand() {
              ExecutorService executor = Executors.newCachedThreadPool();
              for(int i = 0; i < 1; i++) {
                   executor.execute(new ThousandThread(sum));
              executor.shutdown();
              while(!executor.isTerminated()) {
              System.out.println(sum);
         public static void main(String[] args) {
              new Thousand();
         class ThousandThread implements Runnable {
              public  ThousandThread(Integer sum) {
                        sum = 5;
                        System.out.println(sum);
              public void run() {
                   System.out.println("in Thread : ");
    }

    AlyoshaKaz wrote:
    here's the exact queston
    (Synchronizing threads) Write a program that launches one thousand threads. Each thread adds 1 to a variable sum that initially is zero. You need to pass sum by reference to each thread.There is no pass by reference in Java
    In order to pass it by reference, define an Integer wrapper object to hold sum. This is not passing by reference. It is passing a reference by value.
    If the instructor means that you are to define a variable of type java.lang.Integer, this will not help, as Integer is immutable.
    If, on the other hand, you are meant to define your own Integer class (and it's not a good thing to use a class name that already exists in the core API), then you can do so, and make it mutable. In this case, passing a reference to this Integer class will allow your method to change the contents of an object and have the caller see that change. This ability to change an object's state and have it seen by the caller is why people mistakenly think that Java passes objects by reference. It absolutely does not.
    Bottom line: Your instructor is sloppy with terminology at best, and has serious misunderstanding about Java and about CS at worst. At the very least, I'd suggest getting clarification on whether he means for you to use java.lang.Integer, which might make the assignment impossible as worded, or if you are supposed to create your own Integer wrapper class.
    Edited by: jverd on Oct 27, 2009 3:38 PM

  • Passing Inner class name as parameter

    Hi,
    How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
    Hope somebody can help me.
    Thanks in advance.
    Prem

    No, because an inner class can never have a constructor that doesn't take any arguments.
    Without going through reflection, you always need an instance of the outer class to instantiate the inner class. Internally this instance is passed as a parameter to the inner class's constructor. So to create an instance of an inner class through reflection you need to get the appropriate constructor and call its newInstance method. Here's a complete example:import java.lang.reflect.Constructor;
    class Outer {
        class Inner {
        public static void main(String[] args) throws Exception{
            Class c = Class.forName("Outer$Inner");
            Constructor cnstrctr = c.getDeclaredConstructor(new Class[] {Outer.class});
            Outer o = new Outer();
            Inner i = (Inner) cnstrctr.newInstance(new Object[]{o});
            System.out.println(i);
    }

  • Pass C++ Class Member Function as a callable function in AIR Native Extension

    I'm writing an ANE and I'd like to know if anyone has been able to pass a C++ class member function pointer as a callable function from AIR? I have tried this so far with a little bit of C++11 trickery and it's crashing. I've also statically linked the libstdc++ into my library, according to the documentation, in order to ensure that these features I use work correctly. I have code like so:
    FakeWorld* world = new FakeWorld();
    *numFunctions = 1;
    memberFunctions = (FRENamedFunction*) malloc(sizeof(FRENamedFunction) * (*numFunctions));
    ANEMemberFunction mCreateFakeBody = std::tr1::bind(&FakeWorld::createFakeBody, world, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4);
    ANEFunction* createFakeBody = mCreateFakeBody.target<ANEFunction>();
    memberFunctions[0].name = (const uint8_t*) "createFakeBody";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = createFakeBody;
    FRESetContextNativeData(ctx, (void*)world);
    I just realized I'm using C here for allocating the member functions array.. silly me, but I don't think this is the cause of my issue. I refuse to believe that Adobe has built to the Native Extensions portion of the runtime in such a way that I have to cram every single function I want to create (natively) into a global, C formatted namespace (Especially since the documentation says that C is only required for the extenion and context initializing function interfacing and the rest of the code can be done in C++ or objective-C). So please let me know if and how this is possible and I thank you so much in advance for your time!P.
    P.S. Currently when I run this code, I can do the object initialization just fine. As soon as I invoke the "createFakeBody" method on the native side, the runtime dies and simply says:
    Problem signature:
      Problem Event Name: BEX
      Application Name: adl.exe
      Application Version: 3.1.0.4880
      Application Timestamp: 4eb7612e
      Fault Module Name: StackHash_0a9e
      Fault Module Version: 0.0.0.0
      Fault Module Timestamp: 00000000
      Exception Offset: 00000000
      Exception Code: c0000005
      Exception Data: 00000008
      OS Version: 6.1.7601.2.1.0.256.48
      Locale ID: 1033
      Additional Information 1: 0a9e
      Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
      Additional Information 3: 0a9e
      Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
    Read our privacy statement online:
      http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
    If the online privacy statement is not available, please read our privacy statement offline:
      C:\Windows\system32\en-US\erofflps.txt
    Thanks again for your assitance.

    It's been a little while since i've dealt with C++ and not up to speed on tr1 or C++0x, so forgive me if i'm not helping.
    The the examples of std::tr1::bind that i'm seeing out there seem to be either dereferencing the bound 'this' pointer when creating the bound method, i.e. in your case *world instead of world, or using std::tr1::ref(*world), therefore i believe that bind expects the bound parameters to be passed by reference.
    Given that the result of std::tr1::bind is callable (basing that on http://stackoverflow.com/questions/3678884/virtual-member-functions-and-stdtr1function-how -does-this-work) could you simplify to the following:
    memberFunctions[0].name = (const uint8_t*) "createFakeBody";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = std::tr1::bind(&FakeWorld::createFakeBody, *world, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4);
    Or for an even simpler starting point, creating a test member function 'helloWorld' in FakeWorld that takes no arguments and using:
    memberFunctions[0].name = (const uint8_t*) "helloWorld";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = std::tr1::bind(&FakeWorld::helloWorld, *world);
    Hope this helps.

  • While creating Projects Using the API, get two errors: 'Customer name must be passed' and 'class category is invalid'

    Hi
    While trying to Create Projects using the API, I'm getting two types of errors -
    The first is : 'API failed in one stage 1 Customer Name is a mandatory Quick Entry field. Value must be passed'
    The second is : '
    'API failed in one stage 1 Project: '<Project_Number>'
    The class category is invalid.'
    Both the messages are produced by our custom program. .. however I am not able to understand why the underlying errors occur.
    The first error ( Customer Name is a mandatory quick entry field), is caused by Projects that are to be created from Project templates where it is configured with Quick Entry Customer Name required. We are passing Customer Site number ( Party Bill to site number and Party Ship to side number). The site numbers being passed are also set as 'Primary'. Yet they are failing.
    For the second Error ( The Class Category is invalid), I rechecked multiple times, the Class categories for the Projects I am trying to create, with the Config in R12 and they are fine. Can't understand the reason for these two issues. Has anyone encountered such an issue ? If so how was it resolved?
    Regards
    Vivek

    HI All
    I resolved both the issues. In case there are others facing similar issues, following was the cause and resolution of my errors
    1. Error 1: Customer Name is a Mandatory Quick Entry field. Value must be passed.
    The cause was that the data loaded into our custom staging table was not in the right fields. This was because the data file values and the CTL were not in sync.
    Resolution:
    Corrected the data file to be in Sync with the structure defined in the CTL and  this loaded it successfully
    2. Error 2: The class category is invalid.
    The cause of this error was that  in the  Projects Template (used to create the project from), the Quick Entry setup had a Class Category set as required and I was not passing a value ( a class code value) for that Class Category.
    Hope this helps somebody else
    Cheers
    Turnbill

  • Trying to pass a class as a parameter

    I am converting code written by someone else in VB6.  They had a lot of global variables and I am trying to find a way to use a class as a parameter so I can pass it to multiple forms.  I can’t get the method to accept the class.
    Here is the class definition:
        public class CommonCode
            public class gArrayContainer
                public gArrayContainer()
                    dateTimeInputRecord = null;
                    strPanelData = null;
                    strTimeSelected = null;
                    strPanelPresent = null;
                public gArrayContainer(int intNumberOfInputRecords)
                    dateTimeInputRecord = new DateTime[intNumberOfInputRecords];
                    strPanelData = new string[intNumberOfInputRecords, 4, 25, 8, 17, 12];
                    strTimeSelected = new string[intNumberOfInputRecords];
                    strPanelPresent = new string[intNumberOfInputRecords, 4, 25];
                public DateTime[] dateTimeInputRecord { get;set; }
                public string[,,,,,] strPanelData { get; set; }
                public string[] strTimeSelected { get; set; }
                public string[,,] strPanelPresent { get; set; }
                public string strTest {get; set;}
    This is where I am calling from:
    private
    void openBarButtonItem_ItemClick(object
    sender, DevExpress.XtraBars.ItemClickEventArgs e)
    try
    CommonCode cmn =
    new
    CommonCode();
                    CommonCode.gArrayContainer
    gArrayContainerInstance = new
    CommonCode.gArrayContainer();
                    cmn.mnuFileOpen(CallMe, gArrayContainerInstance);
    catch (Exception
    exc)
    Console.WriteLine(exc);
    throw exc;
    And this is the method I’m trying to call:
    public
    void mnuFileOpen(PassStatusBackFunction
    messageCallback, gArrayContainerInstance )
    try
    string strStartDirectory =
    string strDataPath =
    string strDataFile =
    string strDataFileTitle =
    int intCount = 0;
                    additional logic……
    catch (Exception
    exc)
                    Console.WriteLine(exc);
    throw exc;
    How am I supposed to code the class in the calling location and the definition?
    Thanks.

    Also (not sure why you've chosen c#) it would be far easier for you to convert from VB6 to VB.Net than it would be to C#, I even think theres some pretty robust converters knocking around the tinterweb

  • How to pass a Class as a parameter of a method?

    I have a method like below. Inside this method I need to create a variable that his type is the type of the class I have passed as a method's parameter.
    For example, if I call the method like this "Meth1(ClassPerson);" insed the method I need to declare a  variable of class "ClassPerson", but if I call like "Meth1(ClassCity);" I need the same variable to be declared as a ClassCity.
    public function Meth1( /*I dont know what to put here*/   ):void{
         /*I dont know what to put here to declare my variable*/
         /*here
         comes
         more
         code
         using
         the
         variable*/
    I tried as below but dont worked:
    public function Meth1( classtype:Class):void{
         var var1:classtype = new classtype();
    Can someone help me?

    evyatarBH, after declare the variable like you said an error occurs when I try to access some property of the variable. I receive a mesage telling that this property dont exists.
    public function Meth1( classtype:Class ):void{
         var var1:* = new ClassFactory(classe);
         //when I try to do something like the line below the error appear
         inputtext1.text = var1.fieldname;
    rashare, I can't do this because I can't declare the object before the method is called. I must inform to the method only which class I will use, but the object must be created only inside the method.

  • How to pass entire class as a parameter in a method of other class- OpenScr

    Hi Folks,
    Whenever we create a script in OpenScript, it can contain only one class. However I want to declare several variables in a class/script and pass this entire class B as a parameter in a methodA of classA.
    What I mean by mean that is , I create ClassB something like below
    public class MyParams.....
    variable1;
    variable2;
    variable3;
    variable4;
    variable5;
    public class Original.....
    public void methodA(MyParams params)
    params = new MyParams();
    field1 = params.variable1;
    field2 = params.variable2;
    field3 = params.variable3;
    field5= params.variable5;
    Edited by: OATS Explorer on Mar 8, 2012 1:53 AM

    Hi
    I have a stand alone program (can be used by all other users) which will accept request_id and To_Email as parameters. I am developing a new request set in which I want to incldue this stand alone program and want to pass Prog#1 request Id to the 2nd stand alone program as a parameter so that I can send the output of the Prog#1 to the users through E-mail.
    Do we have any options to pass Prog#1 requeset id in to Prog#2 as a parameter in the request set without modifying the stand alone concurrent program code.
    Please note that i dont want to change stand alone program code becuase this code/program was developed to work in general for all the users and I dont want to change this code for new requirement/purpose...
    Hope you understood my requirement...
    Thanks!!

  • How to pass virtual column as an argument for a function in a query as given below

    I want to pass the column MinMark as an argument please help
     Select CASE WHEN MIN(mark1) 
                             <= MIN(mark2) AND MIN(mark1) <= MIN(mark3) THEN MIN(mark1 ) WHEN MIN(mark2) <= MIN(mark3) THEN MIN(mark2) 
                             ELSE MIN(mark3) END AS MinMark
    dbo.ufMarkStatus(a.student,a.term,MinMark )
    from Mark a;
    polachan

    Try the below:
    ;With cte as
    Select a.student,a.term,CASE WHEN MIN(mark1)
    <= MIN(mark2) AND MIN(mark1) <= MIN(mark3) THEN MIN(mark1 ) WHEN MIN(mark2) <= MIN(mark3) THEN MIN(mark2)
    ELSE MIN(mark3) END
    From Mark a
    Group by a.student,a.term
    Select dbo.ufMarkStatus(a.student,a.term,a.MinMark ) From cte a

  • Can not pass CString variable as value argument to exported function in library

    I have extension library having following function exported
    __declspec(dllexport) int MyMessageBox(CString & csText, CString csCaption, const int iMsgType);
    The linker error is coming for second argument when I try to call the function from client.
     error LNK2001: unresolved external symbol "int __cdecl MyMessageBox(class ATL::CStringT<unsigned short,class StrTraitMFC_DLL<unsigned short,class ATL::ChTraitsCRT<unsigned short> > > &,class ATL::CStringT<unsigned short,class
    StrTraitMFC_DLL<unsigned short,class ATL::ChTraitsCRT<unsigned short> > > &,int)" (?MyMessageBox@@YAHAAV?$CStringT@GV?$StrTraitMFC_DLL@GV?$ChTraitsCRT@G@ATL@@@@@ATL@@0H@Z)
    I have checked project settings for both(client as well as DLL) and I think it may not an issue as both are using same character set and linker settings.
    Please help. 

    On 3/26/2015 9:01 AM, AtulPP wrote:
    I have extension library having following function exported
    __declspec(dllexport) int MyMessageBox(CString & csText, CString csCaption, const int iMsgType);
    The linker error is coming for second argument when I try to call the function from client.
      error LNK2001: unresolved external symbol "int __cdecl MyMessageBox(class ATL::CStringT<unsigned short,class StrTraitMFC_DLL<unsigned short,class ATL::ChTraitsCRT<unsigned short> > > &,class ATL::CStringT<unsigned short,class
    StrTraitMFC_DLL<unsigned short,class ATL::ChTraitsCRT<unsigned short> > > &,int)" (?MyMessageBox@@YAHAAV?$CStringT@GV?$StrTraitMFC_DLL@GV?$ChTraitsCRT@G@ATL@@@@@ATL@@0H@Z)
    Use Dependency Walker (http://www.dependencywalker.com/) or dumpbin to discover the decorated name under which the function is actually exported from the DLL, compare with the one the linker
    is complaining about.
    What compiler version are you using? Seeing "unsigned short" where one would expect wchar_t is suspicious. VC6 did that (lacking a built-in wchar_t type), but it wouldn't have things like StrTraitMFC_DLL. I suspect you are building one of the
    two modules with /Zc:wchar_t- (Project > Properties > C/C++ > Language > Treat wchar_t As Built-in Type = No).
    Igor Tandetnik

  • Create an object with the name passed in as a string argument to a method

    Hi,
    I am sorry if it's too trivial for this forum , but I am stuck with the following requirements.
    I have a method
    void abc(String object_name, String key, String value)
    method abc should first check if there exists in memory a hashmap object with the name passed in as argument object_name.
    If yes ..just put the key and value there.
    if not , then create the hashmap object called <object_name> and insert the key/value there.
    Can anybody help me in the first step i.e, how to check if an object exists with the name passed in and if not then create it.
    Will getInstance method be of any help?
    Thanks in advance for your response.
    -Sub-java

    Dear Cotton.m,
    Thanks for your suggesstion. I will remember that.
    But somehow I have a strong belief that you still need to consult dictionary for exact meaning of the words like "upset" , "frustration" etc. Not knowing something in a language , that too as a beginner, does not yield frustration, but increases curiosity. And people like petes1234 are there to diminish that appetite.
    To clarify above, let me compare jverd's reply to my doubt with petes1234's.
    jverd said it cannot be done and suggested a work around (It was perfect and worked for me) While petes1234 , having no work in hand probably, started analysis of newbies mistakes.
    jverd solved my problem by saying that it cannot be done. petes1234 acted as a worthless critic in my opinion and now joined cotton.m.
    Finally, this is a java forum and I do not want to discuss human characteristics here for sure.
    My apologies if I had a wrong concept or if I chose a wrong forum to ask, where people like petes1234 or Cotton.m show their geekdom by pointing out "shortfalls" rather than clearing that by perfect examples and words.
    Again take it easy and Cotton.m , please do not use this forum to figure out others' frustration but be a little more focussed on solving others "Java related" problems :)
    -Sub-java

  • Passing arrayholding classes..

    (Beginner to java requires help..)
    I have this simple class:
    public class Info3d {
    public FloatArrayList[] gcoords = new FloatArrayList[3];
    public IntArrayList triangles = new IntArrayList();
    /** Creates new Info3d */
    public Info3d() {
    gcoords[0] = new FloatArrayList();
    gcoords[1] = new FloatArrayList();
    gcoords[2] = new FloatArrayList();
    triangles = new IntArrayList();
    public void reset() {
    pos = 0;
    tpos = 0;
    And I use it to keep 3d vertex and face information
    But when I pass an instance of this class as a parameter, all the arrays become empty
    How do I make it so that they dont become empty (extending Object didnt work)
    thx

    if you want the entire code of the class:
    package fileconvert;
    import fileconvert.coord;
    import cern.colt.list.IntArrayList;
    import cern.colt.list.FloatArrayList;
    * @author  Admin
    * @version
    public class Info3d {
    public FloatArrayList[] gcoords = new FloatArrayList[3];
    public IntArrayList triangles = new IntArrayList();
    public int pos = 0;
    public int tpos = 0;
    public final static int x = 0;
    public final static int y = 1;
    public final static int z = 2;
        /** Creates new Info3d */
        public Info3d() {
        gcoords[0] = new FloatArrayList();
        gcoords[1] = new FloatArrayList();
        gcoords[2] = new FloatArrayList();
        triangles = new IntArrayList();
        public void reset() {
            pos = 0;
            tpos = 0;
        public void add(Info3d temp) {
            pos = gcoords[0].size();
            int i = pos;
            for(; (pos-i)<temp.gcoords[0].size(); pos++)
                this.gcoords[x].add(temp.gcoords[x].get(pos-i));
                this.gcoords[y].add(temp.gcoords[y].get(pos-i));
                this.gcoords[z].add(temp.gcoords[z].get(pos-i));
            tpos = triangles.size();
            int i2 = tpos;
            for(; (tpos-i2)<temp.triangles.size(); tpos++)
                this.triangles.add(temp.triangles.get(tpos-i)+i);
            this.reset();
        public void writetriangles() {
            if (triangles.size()==0)
                for(tpos=0; tpos<(gcoords[0].size()-2); tpos++) {
                    triangles.add(x);
                    triangles.add(x+1);
                    triangles.add(x+2);
    }I need help urgently...

  • How to inheritance a super class without no-argument constructor

    i try to inheritance javax.swing.tree.DefaultTreeModel:
    public class myTreeModel extends DefaultTreeModel
    but the compiler say:
    'constructor DefaultTreeModel() not found in class javax.swing.tree.DefaultTreeModel'
    and stoped.
    How can I get around this?
    THANK YOU for your consideration.

    Inside myTreeModel, i tried several things:
    1. add a no-argument constructor;
    Your no argument constructor should be either one of the below :
    public myTreeModel() {
       super(new DefaultMutableTreeNode());
    public myTreeModel() {
       super(new DefaultMutableTreeNode(), true);
    2. add a contructor with (DefaultTreeNode) argument;
    Your constructor with tree node argument should be either one of the below :
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node);
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node, true);
    }You would get an error if you did the following:
    public myTreeModel() {
    public myTreeModel(DefaultMutableTreeNode node) {
    }In both of the cases the default no arguement constructor of the super class is called implicitly like:
    public myTreeModel() {
       super();
    public myTreeModel(DefaultMutableTreeNode node) {
       super();
    }In this case the call super() is refering to a no arguement constructor in DefaultTreeModel. However, no such constructor exists in the DefaultTreeModel class resulting in a compile time error.
    Note: You do not need to use DefaultMutableTreeNode. You an use some other class that implements the TreeNode interface.

  • Wrapper Classes as method arguments

    Can some one please explain the behavior below:-
    Source:-
    class Test1
    public static void main(String[] args)
    Test1 inst_test = new Test1();
    int i1 = 128;
    int i2 = 128;
    int i3 = 12;
    int i4 = 12;
    inst_test.method( i1 , i2 );
    inst_test.method( i3 , i4 );
    public void method( Integer i , Integer j )
    System.out.println(i == j );
    Output:-
    false
    true
    Explanation:-
    Here when method() was called first time i got "false" while second time i got "true". In both the cases i passed int values. When i did some research i found that if values are in range of bytes i.e. -128-127 it return true but for values outside this range it returns false.
    Thanks
    Ashwani

    The Java runtime now maintains a small pool of instances of Integer, that happens to contain the exact range you describe. Add autoboxing to that, and you'll see that whenever an int from that range is boxed into an Integer, it's assigned the instance from that pool. Does that make sense?

  • I need a tutor in order to pass my class in Java Programming!

    I'm having a lot of trouble keeping up in my online course. Because there is no class room, I find it difficult to ask questions. The time lap between question and answer makes it extra difficult to concentrate and stay focused on the problem. I would really like someone to be my tutor. Corresponde via email so that I can get help quicker and stay on track.
    I'm suppose to write an array in order to keep inventory. I have no idea where to even start. Here is the assignment, if you can help me and point me in the right direction, or show an example of codes I can use, it would be greatly appreciated.
    1) Create a product class that holds the item number, the name of the product, the number of unites in stock, and the price of each unit.
    Item # 1, Red Hanging Candle Holder, 24, $12.00
    Item # 2, Blue Hanging Candle Holder, 24, $12.00
    Item # 3, Green Hanging Candle Holder, 24, $12.00
    Item # 4, Yellow Hanging Candle Holder, 24, $12.00
    2) Create a Java application that displays the product number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory (the number of units in stock multiplied by the price of each unit).

    God bless, Darryl. My time is more valuable to me.
    Maybe this arrangement works because you need the
    instruction as much as the OP does. The only
    question is: who will provide it? If neither person
    knows more than a month's worth of Java, how is new
    information brought in?
    Thanks duffymo for your blessing. As programming is just a hobby for me -- since 1983 -- I agree that my time is (much much) less valuable than yours. And yes, I expect the learning process to be mutually beneficial. And while I don't plan to make my living off java, I believe in doing things correctly or not at all. My one month experience in Java is backed up by programming in more languages than most professionals use in a lifetime, on platforms starting from pre-DOS systems with CTDs and a single-line display through DOS, xenix, PDP-11, MicroVAX and every version of Windows from 95 onwards.
    In any case, don't you think it would help if the simplest of questions were kept off these forums and solved in mutual self-help groups? some of whose members had nore time than others to spend on Googling and searching the forums? The first benefit would be to those who have progressed beyond the obvious, as you seniors would have more time to answer their pleas for help instead of getting bogged down in badly or unformatted code with all the trappings of cut-n-paste, meaningless comments that seem to be intended more for the teachers than the learners -- I could go on and on.
    I apologise for what I'm about to do; I do really agree with the general feeling on the forums that OPs benefit much more from being guided towards their goal than from being spoonfed a code that works. But I would really appreciate your critique of this code, which is my first console application. It took about half an hour, including Googling. I am aware that there are absolutely no comments, and the output columns don't line up, due to my as yet inadequate knowledge of output formatting. Anything else you can point out would help me in my learning process.
    Thanks for your time, Darryl
    File Inventory.javapublic class Inventory
        public static void main (String args [])
            int[] itemNumbers   = { 1,
                                    2,
                                    3,
                                    4
            String[] itemNames  = { "Red Hanging Candle Holder",
                                    "Blue Hanging Candle Holder",
                                    "Green Hanging Candle Holder",
                                    "Yellow Hanging Candle Holder"
            int[] unitsInStocks = { 24,
                                    24,
                                    24,
                                    24
            double[] unitPrices = { 12.0,
                                    12.0,
                                    12.0,
                                    12.0
            Product[] products = new Product[4];
            for ( int i = 0; i < products.length; i++)
                products[i] = new Product(itemNumbers,
    itemNames[i],
    unitsInStocks[i],
    unitPrices[i]);
    double productValue = 0.0;
    double totalValue = 0.0;
    System.out.println("Item #\t" +
    "Name\t" +
    "Units in stock\t" +
    "Unit price\t" +
    "Total Cost");
    for ( int i = 0; i < products.length; i++)
    productValue = products[i].get_productValue();
    totalValue = totalValue + productValue;
    System.out.println(products[i].get_productDetails() + "\t" +
    Double.toString(productValue));
    System.out.println("");
    System.out.println("\t" +
    "\t" +
    "\t" +
    "Grand Total\t" +
    Double.toString(totalValue));
    File Product.javapublic class Product {
        private int itemNumber;
        private String itemName;
        private int unitsInStock;
        private double unitPrice;
        private Product()
        public Product(int    itemNumberIn,
                       String itemNameIn,
                       int    unitsInStockIn,
                       double unitPriceIn)
            itemNumber   = itemNumberIn;
            itemName     = itemNameIn;
            unitsInStock = unitsInStockIn;
            unitPrice    = unitPriceIn;
        public double get_productValue()
            double unitValue = (double) unitsInStock * unitPrice;
            return unitValue;
        public String get_productDetails()
            String productDetails = Integer.toString(itemNumber) + "\t" +
                                    itemName + "\t" +
                                    Integer.toString(unitsInStock) + "\t" +
                                    Double.toString(unitPrice);
            return productDetails;
    }The forum software seems to have reduced my indentation by 1 space in many lines, they line up correctly in Notepad.
    Message was edited by:
    Darryl.Burke

Maybe you are looking for

  • 17-inch, Mid 2009 mac book pro freezes on startup

    My MBP occasionally freezes on startup. it is a 17-inch, Mid 2009 model details as follows Processor  2.8 GHz Intel Core 2 Duo Memory  4 GB 1067 MHz DDR3 Graphics  NVIDIA GeForce 9600M GT 512 MB Software  Mac OS X Lion 10.7.2 (11C74) The problem firs

  • Adding Wireless to Lan

    I have a LAN w/ a Cisco Pix 501 firewall router and want to add wireless device. I have a Linksys WRT54GS wireless router. Can I use it for this project? When I tried to configure by using the access (wired line) from my desktop - I could not get an

  • How do I change the Sort order for Music Video's on the iPad

    Hi All, Apologies if this has been dealt with elsewhere - I can find posts about sort order for TV Shows and Movies but not Music Video's. When I sync my music video's the appear in Track order in the video app and I cannot find how to change the sor

  • SQL Server 2012 installation problem (error server didn't respond in timely fashion ....)

    Hi everyone, I am new to SQL server....I am learning C# programming using visual studio 2013 . And I want to learn SQL database language to create and practice C# database project....My computer meets all the hardware requirement for SQL installation

  • Selections will not stay selected to be deleted when removing autofill data

    I am trying to delete the autofill bank in my Safari, under the usernames and passwords edit Pan, all the autofill data in the bank is automatically selected (highlighed) but when i click remove All nothing happens, wrong autofill data promts remain.