Help needed about Java Threads ?

Hi,
I have a p2p java program that contains many classes, A.java, B.java, etc. It works fine when i send or recieve to eachother one at a time, but I would like to be able to send/recieve things at the same time. So i would probably need to use Java Threads. Can somebody please show me how this is done. I would really appriciate it. Thanks!!
import java.net.*;
import java.io.*;
import java.lang.*;
public class A {
        private static String hostname; //host name
        public A () { }
       public static void send() throws IOException {
                //send code here
        public static void receive() throws IOException{               
                //receive code here
        public static void main(String args[]) throws IOException {
                //do both send/recieve at the same time?
                send();
                receieve();
}

Well, I think( this is comming out my rear ) that the scope of the recieve() call is not in the main method anymore but instead in class you've created with "new Thread()" and it's throwing from the public void run() instead. This is a good example of complicated code. I would do this:
(Untested code)
import java.net.*;
import java.io.*;
import java.lang.*;
public class A implements Runnable { // <--- NEW
        private static String hostname; //host name
        public A () { }
        public static void send() throws IOException {
                //send code here
        public static void receive() throws IOException{               
                //receive code here
        public static void main(String args[]) throws IOException {
                //do both send/recieve at the same time?
                new Thread( this ).start();
                send();
        /******** NEW ************/
        public void run()
            while( keepListening )
                // It's the assumption that recieve() is
                // throwing the IOException from some net calls
                try {
                   recieve();
                } catch( IOException ioe ) {
                   System.out.println( "IOException in run()\n" + ioe.getMessage();
}

Similar Messages

  • Help needed with java

    Hello everyone
    I'm a Student and new to java and I have been given a question which I have to go through. I have come across a problem with one of the questions and am stuck, so I was wondering if you guys could help me out.
    here is my code so far:
    A Class that maintains Information about a book
    This might form part of a larger application such
    as a library system, for example.
    @author (your name)
    *@version (a version number or a date)*
    public class Book
    // instance variables or fields
    private String author;
    private String title;
    Set the author and title when the book object is constructed
    public Book(String bookAuthor, String bookTitle)
    author = bookAuthor;
    title = bookTitle;
    Return The name of the author.
    public String getAuthor()
    return author;
    Return The name of the title.
    public String getTitle()
    return title;
    and below are the questions that I need to complete. they just want me to add codes to my current one, but the problem is I don't know where to put them and how I should word them, if that makes sense.
    Add a further instance variable/field pages to the Book class to store the number of pages in the book.
    This should be of type int and should be set to 0 in the Constructor.
    Add a second Constructor with signature
    public Book(String bookAuthor, String bookTitle, int noPages) so it has a third parameter passed to it as well as the author and title;
    this parameter is used - obviously?? - to initialise the number of pages.
    Note: This is easiest done by making a copy of the existing Constructor and adding the parameter.
    Add a getPages() accessor method that returns the number of pages in the book.
    Add a method printDetails() to your Book class. This should print out the Author title and number of pages to the Terminal Window. It is your choice as to how the data is formatted, perhaps all on one line, perhaps on three, and with or without explanatory text. For instance you could print out in the format:
    Title: Robinson Crusoe, Author: Daniel Defoe, Pages:226
    Add a further instance variable/field refNumber() to your Book class. This stores the Library's reference number. It should be of type String and be initialised to the empty String "" in the constructor, as its initial value is not passed in as a parameter. Instead a public mutator method with the signature:
    public void setRefNumber(String ref) should be created. The body of this method should assign the value of the method parameter ref to the refNumber.
    Add a corresponding getRefNumber() accessor method to your class so you can check that the mutator works correctly
    Modify your printDetails() method to include printing the reference number of the book.
    However the method should print the reference number only if it has been set - that is the refNumber has a non-zero length.
    If it has not been set, print "ZZZ" instead.
    Hint Use a conditional statement whose test calls the length() method of the refNumber String and gives a result like:
    Title: Jane Eyre, Author: Charlotte Bronte, Pages:226, RefNo: CB479 or, if the reference number is not set:
    Title: Robinson Crusoe, Author: Daniel Defoe, Pages:347, RefNo: ZZZ
    Modify your setRefNumber() method so that it sets the refNumber field only if the parameter is a string of at least three characters. If it is less than three, then print an error message (which must contain the word error) and leave the field unchanged
    Add a further integer variable/field borrowed to the Book class, to keep a count of the number of times a book has been borrowed. It should (obviously??) be set to 0 in the constructor.
    Add a mutator method borrow() to the class. This should increment (add 1 to) the value of borrowed each time it is called.
    Include an accessor method getBorrowed() that returns the value of borrowed
    Modify Print Details so that it includes the value of the borrowed field along with some explanatory text
    PS. sorry it looks so messey

    1. In the future, please use a more meaningful subject. "Help needed with java" contains no information. The very fact that you're posting here tells us you need help with Java. The point of the subject is to give the forum an idea of what kind of problem you're having, so that individuals can decide if they're interested and qualified to help.
    2. You need to ask a specific question. If you have no idea where to start, then start here: [http://home.earthlink.net/~patricia_shanahan/beginner.html]
    3. When you post code, use code tags. Copy the code from the original source in your editor (NOT from an earlier post here, where it will already have lost all formatting), paste it in here, highlight it, and click the CODE button.

  • Help needed about thread priority

    Hello, could someone help me with the priorities in java? I got 10 levels in total(1-10), but I do need at least 20 levels for my multiple threads program.
    Thank you for your kind help in advance.

    First, let me apologize if I am incorrect, but it seems that the native Thread implementation restricts you to 10 priorities regardless.
    However, you can do just about anything you envision, but it will require some implementation on your part.
    You could implement a subclass of thread that contains your priority (which could be from 1-20). You could then maintain a ThreadManager that would store all running threads, and would accept requests to start and stop threads. The ThreadManager could make decisions about which threads to run, which to interrupt, which to sleep, etc., based on your priority value.
    This sounds like alot to swallow, but I'm sure it's doable if you understand threads.

  • Question about java threads programming

    Hi
    I have to develop a program where I need to access data from database, but I need to it using multithreading, currently I go sequentially to each database to access data which is slow
    I have a Vector called systemnames, this one has list of all the systems I need to access.
    Here is my current code, some thing like this
    Vector masterVector = new Vector();
    GetData data = new GetData();
    For(int i =0; i < systemnames.size(); i++)
    masterVector.add(data.getData((String)systemnames.get(i));
    public class GetData
    private Vector getData(String ipaddress)
    //process SQL here
    return data;
    how do i convert this to multithread application, so there will be one thread running for each system in vector, this is speed up the process of extracting data and displaying it
    has any one done this kind of program, what are the precautions i need to take care of
    Ashish

    http://www.google.com/search?q=java+threads+tutorial&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    http://java.sun.com/docs/books/tutorial/essential/threads/
    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html
    http://www.cs.clemson.edu/~cs428/resources/java/tutorial/JTThreads.html
    http://www-106.ibm.com/developerworks/edu/j-dw-javathread-i.html
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].

  • Question about java thread implementation

    Hi All,
    I am comparing the performance of the Dining philosopher's problem
    implemented in Java, Ada, C/Pthread, and the experimental language I
    have been working on.
    The algorithm is very simple: let a butler to restrict entry to the
    eating table, so that deadlock is prevented.
    It turns out that the java code is the winner and it is 2 times faster than C!
    The comparison result really surprised me, and raised a big
    question mark : why java runs so fast? I did not use high-level synchronization
    constructs like Semaphores, atomic variables, etc.
    I vaguely recall that Java thread is actually implemented by the underlying
    system thread library(so on linux, the default would be NPTL, on windows NT threads,
    and on Mac OSX it would be Cthread?). Can no longer remember where I read that.
    Does anyone here have some notions about the Java thread
    implementations(where is this formally explained)? or Does anyone know where
    I can possibly find relevant literature or the answer?
    thanks a lot.
    cheers,
    Tony

    Peter__Lawrey wrote:
    google has lots of information on java threaded.
    One thing java does is support biased locking. i.e. the thread which last locked an object can lock that object again faster.
    This may explain the difference. [http://www.google.co.uk/search?q=java+usebiasedlocking]
    Note: you can turn this option off and other locking options to see if a feature is giving you the performance advantage.
    Personally I have found that real world multi-threaded applications are easier to write in Java, esp. when you have a team of developers. For this reason, alot of C/C++ libraries are single threaded, even when there would be a performance advantage in being multi-threaded (because its just too hard in reality to make it thread safe and faster because of it)I didn't know that, very interesting :-)

  • Help needed about PDF - java

    Hi everybody,
    I just need to know if it's possible (and has been done already :) ) to take a pdf file and, using java, extract all the text boxes of it so that I can then be able to position them in a java application layout (using Swing).
    I need to do that to extract all the information of the text:
    - size of the page
    - position of the text box
    - size of the text
    - font
    - color
    - other attributes
    That's a subject that has already been discussed a lot, but I couldn't find a clear answer to that question in the forum.
    I really need your help, because I already spent a lot of time searching for that, and now I start wondering if it's really possible...
    Thanks a lot in advance for your help.
    Myriam.

    Hi Carlosbenfeito!
    Thanks a lot for your answer!
    I don't know if the pdf document is a pdf form... The only thing I know is that the pdf file I will have to extract the data from will be generated from a Quark document...
    I will try to find out more.
    In the same time, do you know where exactly I can find this Adobe jar? I had a look on their website, but I didn't find it...
    Thanks for your help.
    Myriam

  • Java Web Start help needed about writing files?

    Hi there! I have this java web start app. i have implemented the File Open service succesfully using the JNLP API but i cant seem to get the File Save Service to work. Basically I have an object in the system which I want it to be serialised to a file on the user's desktop.
           FileSaveService fss;
             try {
                 fss = (FileSaveService)ServiceManager.lookup
                                       ("javax.jnlp.FileSaveService");
             } catch (UnavailableServiceException e) {
                fss = null;
            if (fss != null) {
                try {
                FileContents fc = null;
                FileContents newfc = fss.saveFileDialog(null, null,
                fc.getInputStream(), "newFileName.txt");
                FileIO io = new FileIO();
                io.write("new123.nod", r.getTree());  /// my object is r.getTree() !!!
                } catch (Exception e) {
                      e.printStackTrace();
            }My Object (r.getTree) is basically an array. But I cant save it because the saveFileDialog method accepts ObjectInputStream as a parameter?! Any ideas? Thanks!
    Edited by: player123 on Jun 11, 2009 8:56 AM

    does anyone know? It actually doesnt even open the Save dialog?? why is that?

  • Question About Java Threads and Blocking

    I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
    // Test ProcessBuilder
    public class CommandProcessor {
    public static void Run(String[] cmd) throws Exception {
    System.out.println("inside CommandProcessor.Run function...");
    Process p = new ProcessBuilder(cmd).start();
    StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
    StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
    s1.start();
    s2.start();
    //p.waitFor();
    System.out.println("Process Returned");
    Here's the "StreamGobbler" class:
    import java.lang.*;
    import java.io.*;
    // Attempt to make the output of the process go to the message window
    // as it is produced rather that waiting for the process to finish
    public class StreamGobbler implements Runnable {
    String name;
    InputStream is;
    Thread thread;
    public StreamGobbler (String name, InputStream is){
    this.name = name;
    this.is = is;
    public void start(){
    thread = new Thread (this);
    thread.start();
    public void run(){
    try{
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    while (true){
    String s = br.readLine();
    if (s == null) break;
    System.out.println(s);
    //messageWindow.writeToMessageArea("[" + name + "]" + s);
    is.close();
    catch(Exception ex){
    System.out.println("Problem reading stream" + name + "...:" + ex);
    ex.printStackTrace();
    The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
    We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
    while (s1.thread.isAlive() || s2.thread.isAlive())
    // We really don't do anything here
    I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
    Thank you in advance for your help!

    You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
    This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
    I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

  • Help!  about the thread and synchronize

    I have worked on this assignment two days but I just can't get the answer it required
    the src code is given below. Have to modify those codez using the semaphore.java which included in the zip to get the output written in test.out.txt(also in the zip)
    http://adri.justmine.org/243.zip
    can anyone help me on this? the assignment is due tommorrow, and I am already mad......

    Sorry about that.
    Here is the src codes
    import java.util.*;
    *************** Hamlet.java **************************
    class Hamlet extends Thread
    public Hamlet() {
    public void run() {
    System.out.println("HAMLET: Armed, say you?");
    System.out.println("HAMLET: From top to toe?");
    System.out.println("HAMLET: If it assume my noble father's person");
    System.out.println(" I'll speak to it, though hell itself should gape");
    System.out.println(" And bid me hold my peace.");
    *****************Marcellus.java******************************
    import java.util.*;
    class Marcellus extends Thread
    public Marcellus() {
    public void run() {
    System.out.println("MARCELLUS: Armed, my lord.");
    System.out.println("MARCELLUS: My lord, from head to foot.");
    ****************Bernardo.java**********************
    import java.util.*;
    class Bernardo extends Thread
    public Bernardo() {
    public void run() {
    System.out.println("BERNARDO: Armed, my lord.");
    System.out.println("BERNARDO: My lord, from head to foot.");
    ***************Semaphore.java*****************************
    public class Semaphore
    public Semaphore(int v) {
         value = v;
    public synchronized void P() {
         while (value <= 0) {
         try {
              wait();
         catch (InterruptedException e) { }
         value--;
    public synchronized void V() {
         ++value;
         notify();
    private int value;
    ***************CurtainUp.java***************
    import java.util.*;
    import Hamlet;
    import Bernardo;
    import Marcellus;
    public class CurtainUp
    public CurtainUp(int hprior, int bprior, int mprior) {
         Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         // Create the actor threads
         Hamlet hamletThread = new Hamlet();
         Bernardo bernardoThread = new Bernardo();
         Marcellus marcellusThread = new Marcellus();
         // Now set the priorities of the actor threads
         hamletThread.setPriority(hprior);
         bernardoThread.setPriority(bprior);
         marcellusThread.setPriority(mprior);
         hamletThread.start();
         bernardoThread.start();
         marcellusThread.start();
    public static void main(String args[]) {
         // Check to make sure that three arguments are passed in for thread
         // priorities, and make sure that the numbers are within the right range.
         // If they are, create an instance of CurtainUp.
         if (args.length == 3) {
         int hprior = Integer.parseInt(args[0]);
         int bprior = Integer.parseInt(args[1]);
         int mprior = Integer.parseInt(args[2]);
         if ((hprior >= Thread.MIN_PRIORITY && hprior <= Thread.MAX_PRIORITY) &&
              (bprior >= Thread.MIN_PRIORITY && bprior <= Thread.MAX_PRIORITY) &&
              (mprior >= Thread.MIN_PRIORITY && mprior <= Thread.MAX_PRIORITY)) {
              CurtainUp curtainUp = new CurtainUp(hprior, bprior, mprior);
         else {
              System.err.println("Range of priorities 1-10 inclusive");
         else {
         System.err.println("useage: Curtainup <priority1> <priority2> <priority3>");
    ********************tThe output *************************
    java CurtainUp N1 N2 N3where N1, N2, N3 are numbers between 1 and 10 inclusive.
    In your program output:
    1. The order in which Bernardo and Marcellus deliver a shared line
    should depend on which actor has higher priority. E.g.
    java CurtainUp 1 1 2HAMLET: Armed, say you?
    MARCELLUS: Armed, my lord.
    BERNARDO: Armed, my lord.
    HAMLET: From top to toe?
    MARCELLUS: My lord, from head to foot.
    BERNARDO: My lord, from head to foot.
    HAMLET: If it assume my noble father's person
    I'll speak to it, though hell itself should gape
    And bid me hold my peace.
    java CurtainUp 1 2 1HAMLET: Armed, say you?
    BERNARDO: Armed, my lord.
    MARCELLUS: Armed, my lord.
    HAMLET: From top to toe?
    BERNARDO: My lord, from head to foot.
    MARCELLUS: My lord, from head to foot.
    HAMLET: If it assume my noble father's person
    I'll speak to it, though hell itself should gape
    And bid me hold my peace.
    2. If Bernardo and Marcellus have equal priority, it doesn't matter
    which one goes first. E.g.
    java CurtainUp 9 1 1HAMLET: Armed, say you?
    MARCELLUS: Armed, my lord.
    BERNARDO: Armed, my lord.
    HAMLET: From top to toe?
    BERNARDO: My lord, from head to foot.
    MARCELLUS: My lord, from head to foot.
    HAMLET: If it assume my noble father's person
    I'll speak to it, though hell itself should gape
    And bid me hold my peace.
    3. Changing the priority of Hamlet in relation to the priorities of
    Bernardo and Marcellus doesn't make any difference to the order in
    which Hamlet speaks his lines. E.g.
    java CurtainUp 9 2 1HAMLET: Armed, say you?
    BERNARDO: Armed, my lord.
    MARCELLUS: Armed, my lord.
    HAMLET: From top to toe?
    BERNARDO: My lord, from head to foot.
    MARCELLUS: My lord, from head to foot.
    HAMLET: If it assume my noble father's person
    I'll speak to it, though hell itself should gape
    And bid me hold my peace.
    java CurtainUp 9 1 2HAMLET: Armed, say you?
    MARCELLUS: Armed, my lord.
    BERNARDO: Armed, my lord.
    HAMLET: From top to toe?
    MARCELLUS: My lord, from head to foot.
    BERNARDO: My lord, from head to foot.
    HAMLET: If it assume my noble father's person
    I'll speak to it, though hell itself should gape
    And bid me hold my peace.

  • Help needed with Java 1.4 and xml Runtime problem

    I am working on a java 1.3 and JAXP1.1 written code. Now I want to compile and run it using J2SE 1.4. Here are the import statements from the existing code.
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.Locator;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import java.sql.*;
    import java.net.*;
    import java.io.*;
    When I run the existing(using java 1.3 and Jaxp1.1) code I have to include the files crimson.jar and jaxp.jar in the windows 2000 CLASSPATH and works fine.
    But when I compile and run it using J2SE 1.4 which has the built in support for the saxp, I thought that I don't have to specify any CLASSPATH for the new 1.4 so I don't specify any Classpath and it gives me the Microsoft "ClassFactory cannot find the requested class" error which means that even thought the new java 1.4 has the xml classes as libraries yet it still requies some .jar files to be listed in the CLASSPATH.
    If I am right then what path will work(i.e what jar class I need to add to the CLASSPATH).
    Thanks for your help.
    RA.

    Thanks for your reply,
    I think I didn't specify when the error occurs. The ClassFactory related error occurs when I run the program, it compiles without any error.
    From what I understood somewhere in the java 1.4 docs, that the new 1.4 has the xml libraries built in by default so one doesn't need to give the classpaths just like we don't give any CLASSPATH for using swing and many of the other java packages. That is one thing.
    Second thing is that I also tried to use the java_xml_pack-spring02 and java_xml_pack-summer02; but non of them include the crimson.jar and the jaxp.jar files in them which are the 2 .jar files that makes the program run fine when used under the java 1.3 with combination of the jaxp1.1(which was downloaded seperately and then the CLASSPATH for it was set.).
    Can you please help what .jar files do I need to use instead. I tried to use the ones that the new java_xml_pack-spring02 and java_xml_pack-summer02 has for the jaxp in them.
    Thanks again.
    RA

  • Help Needed for Java Project

    I have to do a project in my final year Computer Engineering. Can someone give me any ideas about project(to be done in Java)? If anyone can help me with any idea, please do so. Thank You!!

    Hi,
    I did a project on jsp and EJB called Dataminig implemented in Online shopping. Dataminig is an upcomming technology for Customer Relationship management. You can also do some kinda project like online patient monitering. In this project you can even see how to communicate through COM port.

  • Help need in Java Web Service method receiving object values as null

    Below is my web method and Package is the object received from dotnet client as a consumer. I have also defined the Package object structure. Now when I receive the data from dotnet I get only identifier value, but I get ownerid and price as null, even both values are sent by Dotnet client. I want to know whether only primitive datatype in java web service works or I need to do some configuration changes in order to have build in Wrapper class datatypes? It would be a great help if somebody explains.
    @WebMethod
    @WebResult(name = "PackageId")
    public long createNewPackage(@WebParam(name = "Package") com.db.radar.wl.data.Package data1,@WebParam(name = "PackageDetail") PackageDetail data2,@WebParam(name = "PackageTrade") PackageTrade data3);
    public class Package {
    Long ownerid;
    Double price;
    long identifier;
    }

    Hi ,
    I am getting the same error. I am running my application on jboss-4.0.4.GA. Please let me know the version of jboss that you to got it working.
    Thanks
    Viv

  • Help needed in Java Printing Service

    I need to print an image using the new JPS API, but with specific requirements.
    I managed to find out how to get the image printed from my HD onto the printer by using the example given in the JPS user guide. But I can't seem to find out how to achieve the most important requirement.
    I need to be able to control the printing position as well as the printed size of the image. Can anyone help me with it? I can't seem to find proper documentation that is related to the topic.
    Thanks in advance.

    I tried using the MediaSize class by constructing a custom sized media. But when I compiled it, I kept getting a "cannot resolve symbol" error for MediaSize.
    Then returning to the MediaSize documentation page, it said that it is not yet used to specify media. Does that mean I have to wait?
    The other thing is, I tried another approach using the java.awt.print package. Can you help me out with this piece of code, how do I correct it :
    Paper paper = new Paper();
    PageFormat page = new PageFormat();
    paper.setImageableArea(0,0,600,800);
    page.setPaper(paper);
    DocPrintJob printJob = pservices[0].createPrintJob(); *
    printJob.setPrintable(this,page);
    I am using the javax.print package on the * line, but the rest is from the java.awt.print method. However, I kept getting a "non-static variable cannot be referenced from a non-static context" error.
    What's wrong? Thanks.

  • Help needed - beginner Java programmer using SUN JDK1.5.0

    I have three intacting classes called CalculatorInterface.java which calls methods in Client.java and Account.java.
    CalculatorInterface-->Client (arrays of objects) c[ ]-->Account (arrays of objects a[ ] linked to c[ ]
    The problem description :
    I have in CalculatorInterface.java
    public class CalculatorInterface
    // reference to class Client
    private static final int maxClients = 4;
    // constructor for client[] object array
    private static client[] c = new client[maxClients];
    private static int total,atotal;
    private static int noClients;
    etc
    etc
    public static void main (String[] args)
    parameter definitions
    code lines
    c[noClients] = new client();
    / creates a new instance of client contained in c[]
    total = noClients;
    code lines
    method calls
    noClients++; // next c[]
    termination
    } // end of Main
    CalculatorInterface Methods including
    void WhatIsLeft()
    ... code ...
    ....code...
    c[total].getAccount(atotal).setAmount_IS_Surplus(c[total].calcWeeklySurplus(salaryYrly,weeklyExpenses,isRes));
    ... code...
    The line of code returns a NullPointerException and crashes the program !!! >_<
    is not successfully calling methods in Account.java ..... ?????
    === === === === === === > AND : I have in Client.java
    public class client
    // references to object Account a[]
    private static final int maxAccounts = 3;
    private Account[] a = new Account[maxAccounts]; //? This references a[] to client
    Client Methods including
    public Account getAccount(int num)
    return a[num]; // will be num = 0 or 1 or 2
    } // end client
    === === ==== ===> AND in Account.java
    public class Account
    Account methods
    SO ..... what's the fix ?

    Hi,
    This forum is exclusively related to discussions about creator .
    You may post this thread here
    http://forum.java.sun.com/forum.jspa?forumID=31
    MJ

  • URGETN HELP NEEDED! JAVA APPLET READING FILE

    Hi everyone
    I need to hand in this assignment today
    Im trying to read from a file and read it onto the screen, my code keeps showing up an error
    'missing method body, or declare abstract'
    This is coming up for the
    public statuc void main(String[] args);
    and the
    public void init();
    Here is my code:
    import java.io.*;
    import java.awt.*;
    import java.applet.*;
    public class Empty_3 extends Applet {
    TextArea ta = new TextArea();
    public static void main(String[] args);
    public void init();
    setLayout(new BorderLayout());
    add(ta, BorderLayout.CENTER);
    try {
    InputStream in =
    getClass().getResourceAsStream("test1.txt");
    InputStreamReader isr =
    new InputStreamReader(in);
    BufferedReader br =
    new BufferedReader(isr);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    String line;
    while ((line = br.readLine()) != null) {
    pw.println(line);
    ta.setText(sw.toString());
    } catch (IOException io) {
    ta.setText("Ooops");
    Can anyone help me please?
    Is this the best way of doing this? Once i read the file i want to perform a frequency analysis on the words so if there is a better method for this then please let me know!
    Thankyou
    Matt

    Whether it is urgent or not, does not interest us. It might be urgent for you but for nobody else.
    Writing all-capitals is considered shouting and rude.
    // Use code tags for source.

Maybe you are looking for

  • Acrobat Forms with Javascript

    I have a form that I would like to have required fields before saving or print. I am really new to javascript coding and know nothing about syntax. I do have some experience with basic html, but this form will not be used online. It will get emailed,

  • Systems are not available in the NWDS but in the Web-client

    I'm at presnt using the VC 7.11 in the web client. For enlarging the default components by a couple of own one I'm trying to use VC in the NWDS. Now I'm facing the problem that the default systems (Busniess Objects, Portal Content, Portlet Applicatio

  • After update to iOS 5 my iPad-1 can't add new events to Calendar and Contacts

    After update to iOS 5 my iPad-1 (and iPhone 4) lost "+" symbol to add new events to Contacts /stock iOS-5 Contacts app/, and can't edit old contacts -  i can't change user photo, can't add phone number, ect.and thereis no opportunity to add new conta

  • Can't switch audio tracks after updating to Yosemite

    Previously, I was able to choose different audio tracks in the QuickTime Player (for instance, director commentary or stereo vs. surround sound) in Mavericks, but now after updating to Yosemite, whenever I try to change the language/track by using th

  • Adobe reader 9.2 wont download.

    There is no error message. I get dialog box that says please wait for set-up, but nothing happens. I am using windows XP and have a new motherboard, faster processor, and plenty of memory after computer crashed last month. Please help! I am also usin