*Basic* Java help needed...

I feel like a complete novice for posting this kinda stuff, but i figured somebody would take 5 minutes and help me out. My final in my programming class depends on 2 programs, one of which is giving me some actual trouble.
What I have to do is create a java applet that allows a user to input their weight, select a planet, and then have their weight converted to what their weight would be on the selected planet. However, if the ouput is higher than 60 pounds, I need a picture of the michelin man to appear and the theme from star wars to play. If it is below 60, A multicolored asterisk should be displayed with applause.
I will post what code I have already made. Please note: ITS VERY VERY BASIC. I may have overcomplicated some things, and there is always more than one way to do something (in my experience). Also, I kinda just converted a temperature conversion applet, so there may be some extra stuff I don't need.
Please help.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class tempsapp2 extends Applet implements ActionListener
Label prompt1;
TextField input1;
Label prompt2;
TextField input2;
int number1, number2;
int mercury, venus, earth, mars, jupiter, saturn, neptune, uranus, pluto, result;
public void init()
prompt1 = new Label ("Enter your weight:");
add (prompt1);
input1 = new TextField (10);
add (input1);
prompt2 = new Label ("Enter the Number of the Planet you would like to have your weight converted to:");
add (prompt2);
input2 = new TextField (10);
add (input2);
input2.addActionListener(this);
add (input2);
public void paint (Graphics g)
number1 = Integer.parseInt(input1.getText());
number2 = Integer.parseInt(input2.getText());
mercury = (number1*3780)/1000;
venus = (number1*9070)/1000;
earth = (number1*10)/1000;
mars = (number1*3770)/1000;
saturn = (number1*9160)/1000;
uranus = (number1*8890)/1000;
neptune = (number1*1125)/1000;
jupiter =  (number1*2364)/1000;
pluto = (number1*670)/1000;
if(number2==1)
g.drawString("Your weight on Mercury would be "+mercury+" lbs",100,150);
else if(number2==2)
g.drawString("Your weight on Venus would be "+venus+" lbs",100,150);
else if(number2==3)
g.drawString("Your weight on Earth would be "+earth+" lbs",100,150);
else if(number2==4)
g.drawString("Your weight on Mars would be "+mars+" lbs",100,150);
else if(number2==5)
g.drawString("Your weight on Jupiter would be "+jupiter+" lbs",100,150);
else if(number2==6)
g.drawString("Your weight on Saturn would be "+saturn+" lbs",100,150);
else if(number2==7)
g.drawString("Your weight on Uranus would be "+uranus+" lbs",100,150);
else if(number2==8)
g.drawString("Your weight on Neptune would be "+neptune+" lbs",100,150);
else if(number2==9)
g.drawString("Your weight on Pluto would be "+pluto+" lbs",100,150);
public void actionPerformed(ActionEvent evt)
  number1 = Integer.parseInt(input1.getText());
  number2 = Integer.parseInt(input2.getText());
  repaint();
}

I am guessing that you are wondering where to go from here. If so http://java.sun.com/products/plugin/1.5.0/demos/applets/Animator/Animator.java may prove helpful.
Also I would recommend using arrays of planet names and weight multipliers. It could make your code a lot less cumbersome.

Similar Messages

  • Psuedocode to java. help needed if poss

    i need to convert the following into java, but i am not sure how to output it..
    Roll a 12 sided die to choose a number between 1...12
    while the user has not made an incorrect guess
    ask the user if the next number will be higher or lower
    choose random number
    if users guess is correct
    increment count of correct guesses
    update the stored current number
    end if
    end while
    tell the user how many correct guesses there are
    any help would be greatful, i am a beginning so go easy!!!
    thanks alot
    stevie

    hey, sorry if i've caused a 'cross post', i am not too sure what it is but i hope i haven't done anything wrong! so far i am just trying to put a basic program together before building on it..
    import java.util.scanner;
    public class dice
    public static void main (String [] args)
    Scanner in = new Scanner(System.in);
    Random rnd = new Random();
    System.out.print("input a number between one and twelve")     int r =in.nextInt;
                   int r = rnd.nextInt(12) + 1;
              System.out.println(r);
    i know this has errors, but i was just hoping for a hint/clue for the basic program before researching more to build on it.. hope this code will help. reply when you can, thank you very much
    stevie

  • Java help needed-Inventory System

    I urgently need help in finishing my java inventory project for school. Can anyone help me usin files and streams to get the program to save data and help me get the menu to work pls THANKS> Heres the source code below:
    // TextForm.java
    // A simple label/field form panel
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class TextForm extends JPanel {
    private JTextField[] fields;
    // Create a form with the specified labels, tooltips, and sizes.
    public TextForm(String[] labels,
    int[] widths, String[] tips) {
    super(new BorderLayout());
    JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
    JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
    add(labelPanel, BorderLayout.WEST);
    add(fieldPanel, BorderLayout.CENTER);
    fields = new JTextField[labels.length];
    for (int i=0; i < labels.length; i+=1) {
    fields[i] = new JTextField();
    if (i < tips.length) fields.setToolTipText(tips[i]);
    if (i < widths.length) fields[i].setColumns(widths[i]);
    JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
    lab.setLabelFor(fields[i]);
    labelPanel.add(lab);
    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
    p.add(fields[i]);
    fieldPanel.add(p);
    JScrollBar JScrollBar = new JScrollBar();
    JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);
    add(vbar, BorderLayout.EAST);
    public String getText(int i) {
    return( fields[i].getText() );
    public static void main(String[] args) {
    String[] labels = { "115ml Medicine", "236.60ml Water-clear", "236.60 Water-Amber", "250ml Irish Moss",
    "250ml Sauce", "355ml Water", "380ml Juice", "473ml Vinegar", "500ml Water", "500 ml Blue Water", "600ml Water",
    "750ml Syrup/honey", "900ml Disinfectant", "1000ml Syrup", "1500ml Water", "Total # caps:" };
    int[] widths = { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 ,12 };
    String[] descs = { "", "Enter Quantity" };
    final TextForm form = new TextForm(labels, widths, descs);
    JButton submit = new JButton("Save Inventory");
    JButton cancel = new JButton( "Cancel");
    submit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record?");
    JOptionPane.showMessageDialog(null, " Inventory status updated");
    JOptionPane.showConfirmDialog(null, "Do you want to exit?");
    JFrame f = new JFrame("Sweet Inventory System");
    f.getContentPane().add(form, BorderLayout.NORTH);
    JPanel p = new JPanel();
    p.add(submit);
    f.getContentPane().add(p, BorderLayout.CENTER);
    f.pack();
    f.setVisible(true);
    Its error free except i cant see the menubar or get it to save items usin files and streams.
    HELP PLEASE

    TELL ME THE CODE I CAN USE TO MAKE IT SAVE ITEMS LIKE
    IN A TEXT FILE AND HOW CAN I ATTACH IT TO THE SAVE
    BUTTON USIN A LISTENER
    THANKS
    PLS POST HEREPosts like this make me ignore you forever.

  • Calling perl script from java ---help needed

    I haven't been doing a lot with java lately and i'm building an app with netbeans and having some difficulty with my button calling an outside perl script I'm pasting the code and error below...any help would be greatly appreciated. It's running on fedora 9 pretty much default install...
    thanks.
    code:
    Runtime r = Runtime.getRuntime();
    Process p = null;
    String s = null;
    String cmd123[] = { "perl /home/deaddev/test1.pl" };
    try {
    p = r.exec(cmd123);
    catch {
    foo bar/etc/etc
    error:
    Oct 12, 2008 4:09:37 PM photomainmgr readToPerlActionPerformed
    SEVERE: null
    java.io.IOException: Cannot run program "perl /home/deaddev/test1.pl": java.io.IOException: error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:474)
    at java.lang.Runtime.exec(Runtime.java:610)
    at java.lang.Runtime.exec(Runtime.java:483)
    at photomainmgr.readToPerlActionPerformed(photomainmgr.java:117)
    at photomainmgr.access$000(photomainmgr.java:21)
    at photomainmgr$1.actionPerformed(photomainmgr.java:54)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
    at java.awt.Component.processMouseEvent(Component.java:6101)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3276)
    at java.awt.Component.processEvent(Component.java:5866)
    at java.awt.Container.processEvent(Container.java:2105)
    at java.awt.Component.dispatchEventImpl(Component.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2163)
    at java.awt.Component.dispatchEvent(Component.java:4288)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
    at java.awt.Container.dispatchEventImpl(Container.java:2149)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4288)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:164)
    at java.lang.ProcessImpl.start(ProcessImpl.java:81)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:467)
    ... 30 more
    error executing perl /home/deaddev/test1.pl

    jschell wrote:
    sabre150 wrote:
    As and alternative you can useString cmd123 = "perl /home/deaddev/test1.pl";Using the single string approach YOU have to do any quoting so with this line no quoting takes place and the script /home/deaddev/test1.pl will be executed.Although that should be true apparently it isn't. I have just run  
    Process p = Runtime.getRuntime().exec("perl /home/sabre/work/dev/perl/xxx.pl");
    new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
    new SyncPipe(p.getInputStream(), System.out).run();
    int returnCode = p.waitFor();
    System.out.println("Return code = " + returnCode);which correctly executes the perl script xxx.pl.
    P.S. SyncPipe is a Runnable that copies an InputStream to an OutputStream.
    Edited by: sabre150 on Oct 14, 2008 9:19 AM
    Interesting! Even though Runtime.exec() works with a single String, ProcessBuilder fails with this approach! You have to split the argument string. This certainly looks like a bug! Some while ago I looked at the source for Runtime.exec() to look at the differences between Runtime.exec() and ProcessBuilder and found that behind the scenes Runtime.exec() uses ProcessBuilder.
    More research is required.

  • Java help needed(PLEASE)

    I have a Question for all you gifted people:
    I am designing a sort of quiz which takes questions and three possible answers from a database(which also holds the real answer).It prints these on the dos screen and I then have a System.in statement which allows the user to enter his or her answer (eg A,B,C or 1,2,3). I need a way of adding up the score at the end!!I was thinking of storing there answers in an array and compairing there answer to my correct answer in the database and if it is the same add 1 and if it not the same add 0???
    How would i write the System.in answers into an array and add them up???
    These are my thoughts on how to do this i would love to hear yours!! And also a help with writing the code for the above system of scoreing would be GREATLY appriciated!!
    thanks everyone,
    james.

    As mathuoa pointed out, since you already display the 3 possible answers to the user, get them into an array and display them on the screen. Then, as the user enters an answer, compare them with the three answers and if it is correct, update the score variable as such. If you want the history of answers that the user has given, then u will have to use a Vector/List/some such collection object to hold the user's answers.
    java.util.Vector answers = new java.util.Vector();
    answers.add(usersAnswer1);
    answers.add(usersAnswer2);
    Then, to get the entries,
    for(Enumeration e = answers.elements(); e.hasMoreElements();)
    System.out.println(e.nextElement());
    //Do something with the answer.
    This is one possible way of getting the answers from the user!

  • Basic DVD Help Needed - More challenging than expected

    Need help creating a basic DVD that a client needs. Here are the specs needed for the DVD:
    No Menu
    No Chapters
    Can scrub forward and backward
    Begins in DVD player in a stopped state
    I can not seem to find an option to remove chapter 1 from the V1 timeline in DVD Studio Pro. Also when DVD is inserted into DVD player the video begins playing right away instead of beginning in a "stopped state" on the DVD player. Any help would be greatly appreciated.

    Make a black menu with a invisible button and link it to your track.
    as for the chapter 1 - you can't get rid of this and is a good thing to have for what your trying to achieve anyways. That way the user can either hit play to start the video or they can hit chapter and it will play as well.
    If you don't want them to be able to push anything other than play on their remote you can disable buttons.

  • Basic Info & Help Needed!

    Hello,
    I recently got Logic Pro, and a TonePort KB37.
    Basically, I can't figure out how to use TonePort on Logic. I see that there's input from it, yet i cannot hear anything.
    I also can't figure out how to record anything.
    If you guys could help me out, I would greatly appreciate it.
    also if you could just offer some basic functions
    like recording with my iBook internal mic or stuff like that, i would like it much.
    thank you in advance
    Cody Trevino

    1)How Do I activate my Plug- Ins?
    Please note that the Toneport DI is preactivated and a license key is not necessary.
    In order to activate your Line 6 Plug-Ins there are a few steps you must take. First, please make sure you have downloaded the latest version of Line 6 Monkey from our website HERE http://www.line6.com/software/ . Once you have the Line 6 Monkey downloaded please plug in the device that contains the plug ins via USB and launch the Line 6 Monkey. On the Optional Add-Ons tab in the Monkey select “Activate Purchase” and paste your License Key in the prompt window. Select “Activate”. Once the Monkey has activated your Plug-Ins you may need to authorize your computer to use them. In the Optional Add-ons tab in Monkey click on the “Authorize” button in the top right corner. For more detailed information please refer to our Gearbox 3.0 set up guide on our website HERE. http://www.line6.com/support/knowledgebase/toneporthelp/

  • Really basic Install help needed, please.

    Assistance would be greatly appreciated.
    Yes, I've searched this whole forum and probably don't know enough to ask the right "search" questions because I haven't found the answers.
    Over the past few months, I've been learning Linux as I now plan to switch from Windows to a Linux distro rather than go with a new computer and Windows 7 and the associated problems.  I have tried several Linux distros individaully side by side with  Windows XP on a partitioned drive.. Most recently I've been using Linux Mint 8 'Helena' and done lots with and to it.  Linux Mint 9 'Isadora' was just released, and since upgrading for a non-rolling distro is a nuisance, I thought I'd try a rolling one. After review and recommendations, I thought I'd give Arch Linux a try. Since most of my computer use is music via a Jukebox (14+k files), browsing, email and info seeking, I don't need all the bells and whistles whith which many distros come. I'm not a gamer.
    Basic Infor:
    PC with 1.4GHz Athlon,  512 Ram, 320 G Hard Drive partitioned equally between Windows XP and Linux (hopefully Arch). High Speed DSL.
    What I need are some really really basic instructions on a side by side install of Arch.
    SOofar, I've got the clock set, and have partitioned my hard drive into
    SDA 1 (my Windows Partition)(160 Gigs
    SDA5                                               1200mb for my swap
    SDA6                                                20 Gigs for the root
    SDA7                                               130 (the rest) Gigs for home
    What I need to know is darned near everything else.
    Bootability for SDA5-7
    How to label (the method for) SDA 5-7
    and thereafter a step by step really simple set of install instructions for a side by side installation.
    I've searched on this forum as well as via Google, but simple  instructions are nowhere to be found. I really have had no trouble installing Mepis, Madriva, Ubuntu, and Linux Mint side by side with my Windows Xp partition and done so for at least 2 of them with manual partitioning rather than the automatic side by side install offered.
    With this introduction, can someone point me to a Arch Linux side by side install for Dummies or help me with a walk through??
    Or am I in completely over my head and need to just go back to Linux Mint and plan to upgrade every 6-18 months? Or try a different rolling Distro???
    Thanks in advance to any and all who can help..
    Dick

    Willie,
    Were I certain I would be happy with Arch, there would be no problem doing as you suggest. However, looking backover at least 2 decades, our first computer was an IBM with an 8086 chip and 20 whole MB of hard drive. The choice of operating systems was DOS. As we moved onwards and upwards, Windows 95, 98, and XP were Hobson's choice for PC users (our office computer used Unix). Now with more experience and research, a new world of operating systems is available, especially for those of us with older computers which would require major (and expensive) upgrades when possible to move to Windows 7. And as with Windows ME, 2000, and Vista, there is probably potential for significant problems with 7. Utilizing my current ability to have 2 (or more) OS's on my computer affords the opportunity to learn more about them and develop my 'geekiness" as well as to evaluate and selectively choose one which will best meet my needs.
    As of now, I have at least 3 problems with abandoing Windows XP completely:
    1) I haven't found a Jukebox program for Linux equivalent to J Rivers' Media Jukebox which has seamless track switching, an equalizer, and DSP studio effects,etc. I've used WINE doors and made it run on Linux Mint, but the program will not recognize my CD-ROM drives. I have some 14+k music files and my computer jukebox runs through my home sound system.
    2) I've some 600+ movies indexed on Movie Organizer (movieorganizer.org) which flat out won't run on the Linux distro's I've tried. Re-entering those 600+ indexed movies to another program will be a bear. So far, no one of my local sources or on the other various Linux forums has a solution. WINE doors won't do it as it needs MDAC. 
    3) For all its frailties and faults, I'm reasonably literate with Windows XP. Linux OS's are still, quite obviously, relatively unfamiliar to me (3 mos experience).. So until I'm much more conversant with Linux, better the devil I know.
    I have installed and used both the Linux Mint 8 Fluxbox and KDE editions on more than one computer so it's not a question of my being shy. BTW, I'm a retired internist, and our speciality is known for being really nitpicky, detail oriented, and investigational, and I'm sure it shows.
    Again, thanks to all for the suggestions and comments. I'll keep in touch.
    Dick

  • Basic form help needed

    I am new to Dreamweaver 8 (but have worked with simple html a
    quite a bit) and am working on building a, hopefully, simple
    prototype for a project. What I need to do is collect user-entered
    text and user-selected dropdown box data on one page and send it to
    another for presentation there. After looking at the Help screens,
    I looked at using Session variables and it seems that is the best
    way to pass the data. Where I am stuck is in the (from Help
    Contents) Making Pages Dynamic - Creating Forms - Creating HTML
    forms help. They first say to, in step 2, Select Insert > Form
    (which doesn't do anything - you have to click another option,
    which I figured meant Form again). Then, in step 3, they say to
    "Specify the page or script that will process the form data." by
    selecting the file in the Action box in Properties. I don't have a
    file to "process the form data" and don't really know what they are
    talking about. Help!
    I originally (before I reverted to using Help) set it up with
    Insert->Form->Text Field text entry boxes, figuring this was
    a Form field that could be captured and passed on. Right? Wrong? I
    guess I thought the method would be to define a variable name
    associated with a text input field in one page, then pass it with
    the value to the next page. That is pretty much what it seems
    Session variables do (?), which I discovered when I started looking
    at Help.
    So, was I on the right track for a simple implementation and
    missed the way to capture and transmit the data, or do I need to
    use the Forms->Forms option? If the former, how do I define the
    variable names? If the later...well, I am real confused then. :-)
    Thanks for your help.
    (btw, we do have training material coming - went with
    Dreamweaver for Dummies, Peachpit Macromedia Dreamweaver 8 Hands-On
    Training "dead tree media" and TechRepublic Fast Track Dreamweaver
    8 CBT. Any opinions on those?)

    Session variables as the name suggests are created when a
    user starts a session and last till the session is open. You form
    doesn't really need session variables unless you are carrying form
    data from one page to another and need to keep it associated with
    that specific user such as in shopping cart applications.
    I have never used the dreamweaver insert form, so can't help
    you there. why not code the form yourself, especially since you
    have been using html
    The link below may help.
    http://www.w3schools.com/html/html_forms.asp

  • Basic Java Help (BufferedReader and PrintWriter)

    I am studying Java for part of my degree and have become quite stuck on a question. I have set up a seperate client class and that appears to work just fine, yet when i come to set up the server class i encounter no end of problems.
    Firstly i have to set up a Server class which handles the communication to the client ;
    import java.net.*;
    import java.io.*;
    public class Server
    private ServerSocket ss;
    private Socket socket;
    //Streams for connections
    private InputStream is;
    private OutputStream os;
    //Writer and reader for communication
    private PrintWriter toClient;
    private BufferedReader fromClient;
    private GameSession game;
    //use a high numbered non-dedicated port
    static final int PORT_NUMBER = 3000;
    //set up socket communication
    public Server() throws IOException
    ss = new ServerSocket(PORT_NUMBER);
    //accept a player connection
    public void acceptPlayer()
    System.out.println("Waiting for player");
    //wait for and accept a player
    try
    while(true)
    //Loop endlessly waiting for client connections
    // Wait for a connection request
    socket = ss.accept();
    openStreams();
    //Client has connected
    game.run(); <-- this i presume runs the method run() from the GameSession Class?
    closeStreams();
    socket.close();
    catch(Exception e)
    System.out.println("Trouble with a connection "+ e);
    private void openStreams() throws IOException
    final boolean AUTO_FLUSH = true;
    is = socket.getInputStream();
    fromClient = new BufferedReader(new InputStreamReader(is));
    os = socket.getOutputStream();
    toClient = new PrintWriter(os, AUTO_FLUSH);
    System.out.println ("...Streams set up");
    private void closeStreams() throws IOException
    toClient.close();
    os.close();
    fromClient.close();
    is.close();
    System.out.println("...Streams closed down");
    // This is the top-level method to handle one game
    public void run() throws IOException
    game = new GameSession(socket);
    acceptPlayer();
    System.out.println("Server closing down");
    } // end class
    which also seems to be about what the question asks, yet i have to link this to the GameSession class sending it a reference of the socket. Which i think i have with the inclusion of the new GameSession(socket).
    When i come to write the GameSession class i realise i have to use the BufferedReader and PrintWriter when i try and do this i get a bindException as obviously the port is up and running from the Server class.
    I have tried incorporating the openStreams() in the GameSession after rermoving them from the Server class but get more Exceptions! What am i doing wron and where would i find more information on this?
    Thanks for any help you may give.

    You must redesign your Server and GameSession class.
    Study this code:
    /* save and compile as GameServer.java */
    import java.net.*;
    import java.io.*;
    public class GameServer{
      static final int PORT_NUMBER = 3000;
      private ServerSocket ss;
      GameSession game;
      public GameServer() throws IOException{
        ss = new ServerSocket(PORT_NUMBER);
        game = new GameSession();
      public void acceptPlayer(){
        System.out.println("Waiting for player");
        try{
          while(true){
            Socket s = ss.accept();
            new Thread(new ClientHandler(s)).start();
        catch(Exception e){
          System.out.println("Trouble with a connection "+ e);
      public static void main(String[] args){
        try{
          GameServer gs = new GameServer();
          gs.acceptPlayer();
        catch (Exception e){
          e.printStackTrace();
      class ClientHandler implements Runnable{
        private Socket socket;
        private PrintWriter toClient;
        private BufferedReader fromClient;
        public ClientHandler(Socket sc){
          socket = sc;
          try{
            fromClient
              = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            toClient = new PrintWriter(socket.getOutputStream(), true);
          catch (Exception e){
            e.printStackTrace();
        public void run() throws IOException{
          game.addNewClient(socket, fromClient, toClient);
    }

  • New to Java:   Help Needed

    Hi,
    I am writing a utility to monitor all the objects created by my application. I want to be able to get not only values of class variables(for which the reflection package seems pretty useful), but also instance variables.
    For example.
    public class myClass {
    //Constructor
    public myClass(int i) {
    // another class instantiates this one
    myClass mc = new myClass(10);
    myClass mc1 = new myClass(20);
    I need to keep track of the the handles mc and mc1 and the
    other initializations they do based on the value passed at runtime.
    Is there a way to to this. Or even better, is there someplace in Java which stores all the objects instantiated and their handles?
    Any suggestions would be greatly appreciated.
    Thnx
    cvsan

    How do I access private and proteced variables. By default only the public variables are accessible via the reflect class as in the example below.
    Class c = rc.getClass();
    String s = c.getName();
    System.out.println(s);
    try { abcField = c.getField("abc");
    where abc is a public instance variable. If abc is a private instance variable, the above example fails.
    Is there any way to override the data hiding feature of Java?
    Thanks
    cvsan

  • Basic Array Help needed

    K all i am trying to do is Make an array of 5 int and then make a small basic test program that returns the smallest index of the matrix. Now the way i am doing this i want to make two files and make a call to the method that i createded called getSmallest of the public class SmallestIndex. The reason i am doing it this way nstead of putting the code in the main method is because i want to learn to pass arrays as parameters . I am learning them for the first time. This is my code:
    import java.util.*;
    import java.io.*;
    public class SmallestIndex
         public static int getSmallest(int[] matrix)
              int minIndex = 0;
              int smallestmatrix;
              for(int index = 1; index < matrix.length; index++)
                   if(matrix[minIndex] < matrix[index])
                        minIndex = index;
                   smallestmatrix = matrix[minIndex];
                   return smallestmatrix;
         public static void fillarray(int[] matrix, int numofelements) throws IOException
              BufferedReader board = new BufferedReader(new InputStreamReader(System.in));
              StringTokenizer tokenizer;
              tokenizer = new StringTokenizer(board.readLine());
              for(int index = 0; index < numofelements; index++)
                   matrix[index] = Integer.parseInt(tokenizer.nextToken());
                   if(!tokenizer.hasMoreTokens())
                        tokenizer = new StringTokenizer(board.readLine());
         public static void printArray(int[] matrix, int numofelements)
              for(int index = 0;index < numofelements; index++)
                   System.out.print(matrix[index] + " ");
    import java.io.*;
    public class TestMatrix
         static BufferedReader board = new BufferedReader(new InputStreamReader(System.in));
         public static void main(String[] args) throws IOException
              int[] matrix = new int[5];
              for(int index = 0; index < matrix.length; index++)
                   matrix[index] = Integer.parseInt(board.readLine());
              System.out.print("Elements");
              SmallestIndex.printArray(matrix, matrix.length);
              //SmallestIndex.fillarray(matrix);
              //SmallestIndex.getSmallest(matrix);

    Here's something slightly different. Compare to yours to see differences
    import java.io.*;
    class SmallestIndex
      public SmallestIndex()
        int[] matrix = fillArray();
        printArray(matrix);
        System.out.println("Smallest          = " + getSmallestNumber(matrix));
        System.out.println("Index of smallest = " + getSmallestIndex(matrix));  
        System.exit(0);
      private int[] fillArray()
        int[] temp = new int[5];
        try
          BufferedReader board = new BufferedReader(new InputStreamReader(System.in));
          for( int x = 0; x < 5; x++)
            System.out.print("Enter a number: ");
            temp[x] = Integer.parseInt(board.readLine());
        catch(Exception e) {System.out.println("error - " + e.getMessage());}   
        return temp;  
      private void printArray(int[] arrayToPrint)
        for(int x = 0; x < arrayToPrint.length; x++)
          System.out.println("Element "+ x + " = " + arrayToPrint[x]);
      private int getSmallestNumber(int[] arrayToGetNumber)
        int smallest = arrayToGetNumber[0];
        for(int x = 1; x < arrayToGetNumber.length; x++)
          if(arrayToGetNumber[x] < smallest)
            smallest = arrayToGetNumber[x];
        return smallest;
      private int getSmallestIndex(int[] arrayToGetIndex)
        int smallest = arrayToGetIndex[0];
        int smallestIndex = 0;
        for(int x = 1; x < arrayToGetIndex.length; x++)
          if(arrayToGetIndex[x] < smallest)
            smallest = arrayToGetIndex[x];
            smallestIndex = x;
        return smallestIndex;
      public static void main(String[] args){new SmallestIndex();}
    }

  • Basic Recording Help Needed!

    I am recording a song that consists of 3 tracks total. I have cut out the parts that are not needed while maintaining the position of the remaining sections. How do I record a final mix that is only one track? Or, how do I burn these tracks to a disc? Basically, I have the recording and editing process done, but now I need to place the music on a disc, or at least have it all saved as one track.
    THANKS!
    LMZ

    Well, I assume since you're in the Logic forum, you are using Logic on your project.
    What you're talking about is called bouncing. This means creating a 2-track mixdown (one track for the left, one for the right). Fortunately, this is easy: just go to File and choose "bounce". From there a window will open giving you several options. If you choose to bounce as AIFF, you can take the resulting file and burn it as an audio CD in Toast or iTunes. Or better yet, you can choose "burn" which will put your smash hit directly on a disc.
    See how easy that was? Now have a pancake.
    macbook pro   Mac OS X (10.4.9)  

  • New to java,,,help needed urgently

    I am geeting a compile error..."cannot resolve symbol" in my main class. The program is supposed to prompt the user for five sets of data, and calculate the tax and total of the entered products and print it back to the screen, it is also supposed to calculate the cheapest and most expensive item and print them back. can someone pls shed some light on this error msg, as I cant seem to get my head around it.
    import java .io.*;
    import java.util.StringTokenizer;
    import java.text.NumberFormat;
    import java.util.Locale;
    //set up a class to call on the constructors from the catalogueitem class
    public class Myassg4
         private static final int MAX = 2;//sets the length to 2
         private static CatalogueItem[] prodlist ;//sets array for product list
         NumberFormat cash = NumberFormat.getCurrencyInstance(new Locale("en","AU"));
         private static void main(String[] args) throws IOException
         {//declare the variables and initialize
         double preTotal = 0.00;
         String inString;
         double maximum, lowest;
         double sum = 0.00;
         BufferedReader stdin = new BufferedReader (new
         InputStreamReader(System.in));
         prodlist = new CatalogueItem[];//sets the length (THIS IS WHERE THE PROBLEM OCCURS!!!!)
    System.out.println("Enter 5 sets of data");
         //loop through the array and read the data in
         for(int i = 0;i <prodlist.length;i++)
              inString = stdin.readLine();
              //create a String Tokenizer to read the data separately
              StringTokenizer tok = new StringTokenizer(inString, ":");
    prodlist[i] = new CatalogueItem(tok.nextToken(), tok.nextToken(),
    Double.parseDouble(tok.nextToken()));
    }//end of loop
    //create a header and print the data back to the screen
    System.out.println();
    System.out.println("LISTING OF ALL GOODS");
    System.out.println();
    System.out.println("Cat\tDescription\tExTax\tTax\tIncTax");
    System.out.println("___\t___________\t_____\t___\t______");
    System.out.println();
    for(int j = 0;j <prodlist.length;j++){
    System.out.println(prodlist[j].getCatno()+"\t"+prodlist[j].getDesc()+
    "\t"+prodlist[j].getPrice()+"\t"+prodlist[j].getTax()
    +"\t"+prodlist[j].getIncTax());
    I have errors every where the prodlist is used, I know I am not initializing it correctly but dont know what the alternatives are.

    daniel here is the entire code if you do get a chance can you pls have a look at it for me thanks.
    import java .io.*;
    import java.util.StringTokenizer;
    import java.text.NumberFormat;
    import java.util.Locale;
    //set up a class to call on the constructors from the catalogueitem class
    public class Myassg4
         private static final int MAX = 2; //sets the length to 2
         private static CatalogueItem[] prodlist; //sets array for product list
         NumberFormat cash = NumberFormat.getCurrencyInstance(new Locale("en","AU"));
         private static void main(String[] args) throws IOException
         {//declare the variables and initialize
         double preTotal = 0.00;
         String inString;
         double maximum, lowest;
         double sum = 0.00;
         BufferedReader stdin = new BufferedReader (new
         InputStreamReader(System.in));
         prodlist = new CatalogueItem[5];//sets the length
         System.out.println("Enter 5 sets of data");
         //loop through the array and read the data in
         for(int i = 0;i <prodlist.length;i++)
              inString = stdin.readLine();
              //create a String Tokenizer to read the data separately
              StringTokenizer tok = new StringTokenizer(inString, ":");
    prodlist[i] = new CatalogueItem(tok.nextToken(), tok.nextToken(),
    Double.parseDouble(tok.nextToken()));
    }//end of loop
    //create a header and print the data back to the screen
    System.out.println();
    System.out.println("LISTING OF ALL GOODS");
    System.out.println();
    System.out.println("Cat\tDescription\tExTax\tTax\tIncTax");
    System.out.println("___\t___________\t_____\t___\t______");
    System.out.println();
    for(int j = 0;j <prodlist.length;j++){
    System.out.println(prodlist[j].getCatno()+"\t"+prodlist[j].getDesc()+
    "\t"+prodlist[j].getPrice()+"\t"+prodlist[j].getTax()
    +"\t"+prodlist[j].getIncTax());
    //use this data and call the cheapest method to print
    //the cheapest goods in the catalogue
    System.out.println();
    System.out.println("CHEAPEST GOODS IN THE CATALOGUE");
    System.out.println();
    lowest = cheapest(prodlist, MAX);
    System.out.println("Cat\tDescription\tExTax\tTax\tIncTax");
    System.out.println("___\t___________\t_____\t___\t______");
    System.out.println();
    for(int k = 0;k <prodlist.length;k++){
    if(prodlist[k].getTaxInc == lowest)
    System.out.println(prodlist[k].Catno()+"\t"+prodlist[k].getDesc()+
    "\t"+prodlist[k].getPrice()+"\t"+prodlist[k].getTax()
    +"\t"+prodlist[k].getIncTax());
    //use the listing of all goods and call the most expensive method
    //to calculate and display back on screen
    System.out.println();//create two lines of space in between
    System.out.println();
    System.out.println("MOST EXPENSIVE GOODS IN THE CATALOGUE");
    System.out.println();
    maximun = expensive(prodlist, MAX);
    System.out.println("Cat\tDescription\tExTax\tTax\tIncTax");
    System.out.println("___\t___________\t_____\t___\t______");
    System.out.println();
    for(int l = 0;l < prodlist.length;l++){
    if(prodlist[l].getTaxInc == maximum)
    System.out.println(prodlist[l].Catno()+"\t"+prodlist[l].getDesc()+
    "\t"+prodlist[l].getPrice()+"\t"+prodlist[l].getTax()
    +"\t"+prodlist[l].getIncTax());
    //print the pretax worth of goods by calling the method and display
    System.out.println();//create a two lines of space in between
    System.out.println();
    System.out.println("TOTAL OF PRE-TAX WORTH OF CATALOGUE ITEMS: "+preTaxWorth
    (prodlist));
    //print the avg tax payable per item
    System.out.println();
    System.out.println("AVERAGE AMOUNT OF TAX PAYABLE PER ITEM:"+avgTax
    (prodlist));
    //declare the other methods within the scope of the main class
    public static double cheapest(CatalogueItem[] prodlist, int size)
         double lowest = prodlist[0].getIncTac();
         for(int i = 0; i < size;i++)
              if(prodlist.getIncTax() < lowest)
              lowest = prodlist[i].getIncTax();
         return lowest;
    public static double expensive(CatalogueItem[] prodlist, int size)
         double maximum = prodlist[0].getTaxInc();
         for(int i = 0; i < size; i++)
              if(prodlist[i].getIncTax() > maximum)
              maximum = prodlist[i].getIncTax();
         return maximum;
    public static double preTaxWorth(CatalogueItem[] prodlist)
    {//add all the getPrice's in together
    double preTax = 0; //prodlist[0].getPrice();
    for(int i =0; i <prodlist.length; i++)
         preTax += prodlist[i].getPrice();
    return preTax;
    public static double avgTax(CatalogueItem[] prodlist)
    {//run through the array and add all the getTax amounts up.
         double sum = 0;
         for(int i = 0; i < prodlist.length; i++)
              sum = sum + prodlist[i].getTax();
         //to get the avg we divide the sum by the MAX number of entries
         double Total = sum / MAX;
         return Total;
    }//end of main class
    //CatalogueItem class      
    //catalogue item class
    //ensure that the accesors and mutators
    //are visible and cannot be overridden
    class CatalogueItem
    //declare the data types
    private String catno;
    private String desc;
    private double price;     
    //declare the taxation rate constant
    //but make it visible
    public CatalogueItem(){
         catno = " ";
         desc = " ";
         double price;
    //declare the full constructor
    CatalogueItem (String inCatno, String inDesc, double Price)
         inCatno = catno;
         inDesc = desc;
         Price = price;
    //name accessor---not overidable
    public final String getCatno()
         return catno;
    //name product description accessor--not overidable
    public final String getDesc()
         return desc;
    //name the extax method
    public double getPrice()
         return price;
    //tax utility method
    public double Tax()
    double Tax;     
         Tax = 00.15 * getPrice();
         return Tax;
    //Including Tax method
    public double IncTax()
         double IncTax;
         IncTax = Tax() + getPrice();
         return IncTax;

  • Set Pasword in any folder through java (HELP NEEDED)

    hi i want know it is possibel in java i m set password in any folder of my windows if it is so reply me soon .
    i m waiting for reply

    In java only - no.
    If there is a command line tool that does it then you can use Runtime.exec() with an OS specific command. Presumably you are talking about windows so you might look in the appropriate resource kit. That is probably the most likely location for a command. But it could be somewhere else too.
    If you can't find a command then you would have to use JNI.

Maybe you are looking for