Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Simple Question

  1. #1
    Junior Member Natural Noob's Avatar
    Join Date
    Oct 2012
    Posts
    1
    My Mood
    Relaxed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Simple Question

    First a little history, I am relatively new to Java. I had a class a few months back but the professor was absolutely horrible at actually teaching and it really turned me off of the subject. Recently I've been looking back through my textbook and decided to get back into it. So I know a bit but not nearly as much as I should after taking an intro class.

    The problem I was working on is a simple stock transaction dealing with buying, selling, and commissions. I am being asked to:
    1. display the amount paid for the stock
    2. the commission paid after buying the stock
    3. the amount the stock sold for
    4. the commission paid after selling the stock
    5. Display the net profit and both transactions and after commission has been paid

    This is one of the first small programs I've written so far:

    PHP Code:
    public class StockTransactionProgram {

        public static 
    void main(String[] args
        {
            
    String input;
            
    int stocksBought;
            
    int stocksSold;
            
    double buyPrice;
            
    double sellPrice;
            
    double comPercent;
            
    double comTotal;
            
    double paid;
            
    double totalPaid;
            
    double sold;
            
    double totalSold;
            
    double netTotal;
            
            
    DecimalFormat formatter = new DecimalFormat("#0.00");
            
            
    input JOptionPane.showInputDialog("How many stocks have been purchased?");
            
    stocksBought Integer.parseInt(input);
            
            
    input JOptionPane.showInputDialog("What price were the stocks bought at?");
            
    buyPrice Double.parseDouble(input);
            
            
    paid stocksBought buyPrice;
            
            
    input JOptionPane.showInputDialog("What is the commission percentage?");
            
    comPercent Double.parseDouble(input);
            
            
    comTotal paid comPercent;
            
            
    totalPaid comTotal paid;
            
            
    System.out.println("You paid " formatter.format(comTotal) + " as a commission.");
            
    System.out.println("And you paid a total of " formatter.format(totalPaid) + " for " stocksBought " shares of stocks.");
             
            
    input JOptionPane.showInputDialog("How many stocks have been sold?");
            
    stocksSold Integer.parseInt(input);
            
            
    input JOptionPane.showInputDialog("What price were the stocks sold at?");
            
    sellPrice Double.parseDouble(input);
            
            
    sold stocksSold sellPrice;
            
            
    input JOptionPane.showInputDialog("What is the commission percentage?");
            
    comPercent Double.parseDouble(input);
            
            
    comTotal sold comPercent;
            
            
    totalSold sold comTotal;
      
            
    System.out.println("You paid " formatter.format(comTotal) + " as a commission.");        
            
    System.out.println("You made a total of " formatter.format(totalSold) + " selling " stocksSold " shares of stocks.");
            
            
    netTotal totalSold totalPaid;
            
            
    System.out.println("Your net total is " formatter.format(netTotal));
        }

    My question is simply is there an easier or more convenient way I could have done this? Or is this good enough for now and worry about convenience when I know a bit more?

    Any tips, tricks, or hints would be greatly appreciated.

    PS. I didn't know if there was an easier way to post my code. This seemed to work fine so I used it. If there is let me know


  2. #2
    Junior Member shadihrr's Avatar
    Join Date
    Jan 2010
    Location
    home
    Posts
    23
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: Simple Question

    I think it is good to use a little object oriented programming. for example create a class "stock" and add for example paid variable in it. In this way you have a better code and you can write more complicated actions on this class easily. And it is good to separate graphic codes with others. It's not good to write for example JOptionPane.showInputDialog in the same place that you calculate comTotal . Again writing classes would help you a lot.

  3. #3
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Simple Question

    Welcome back to the fun of java and to the forum!

    There are many helpful tips for the use of this forum in the Announcements thread, including posting code with tags so it looks like this:
    /** FILE: Apple.java */
    package testing;
     
    /**
     * @author jps
     *  This class represents an apple...
     */
    public class Apple {
     
    	/**The approximate diameter of the apple represented in inches*/
    	public double diameterInInches;
     
    	/**True if the apple has a worm, false otherwise*/
    	public boolean hasWorm;
     
    	/**True if the apple has a great taste, false otherwise*/
    	private boolean greatTaste;
     
     
    	/** Constructs an Apple object:
    	 * @param diameterInInches The diameter of the apple measured in inches.
    	 * @param hasWorm True if the apple has a worm in it, false otherwise.
    	 */
    	public Apple(double diameterInInches, boolean hasWorm) {
    		this.diameterInInches = diameterInInches;
    		this.hasWorm = hasWorm;
    		this.greatTaste = true;//of course my perfect apples have great taste!
    	}
     
     
    	/** @return True if the apple has a great taste, false otherwise. */
    	public boolean hasGreatTaste() {
    		return greatTaste;
    	}
     
     
    	/** @param greatTaste Set the great taste of the apple. */
    	public void setGreatTaste(boolean greatTaste) {
    		//this.greatTaste = greatTaste;
    		this.greatTaste = true;//I am a crooked salesman :P
    	}
     
     
    }
    I used a class I wrote for another topic as an example here because it demonstrates some things which may help you out.

    1) Javadoc comments begin with /** and end with */
    -Search keyword "Javadoc"

    2) This class is part of the package named testing, merely a folder style hierarchy for organization.
    -Search keywords "Java packages"

    3) The instance variables diameterInInches, hasWorm, and greatTaste are declared private.
    -Search keywords "Java access modifiers"

    4) The private variables in this sample class have public getters and setters. (not all are included) The getter is merely a method for returning the value of the variable. The setter is merely a method for setting the value of the variable. While it is possible to say greatTaste = true from within this class, if you create an apple object of this class inside another class, you would not be able to access the variables without the getters and setters. You also maintain control over your variables by limiting access to variables through the methods as was the point of the thread the class was made for. In this case the crooked salesman who wrote the code altered the method used for customer review to force all reviews to say every apple has great taste.
    -Search keywords "Java getters and setters"

    5) This class has a constructor which requires parameters. This means all apple objects are required to provide values for the size and if there is a worm.
    -Search keywords "Java constructor parameters"

    6) The basic design of a Java class. Most classes I write basically LOOK the same. There is always a comment on the top of the page stating the name of the saved file. The comment just above the class declaration includes the @author and a description of the purpose and use of the class. Every part of the class has comments, constructors, methods, variables, what ever you find. At first the seemingly endless comments make the code feel cluttered but in time your eyes get used to them and code without them seems naked. As someone starting out, get used to using comments early. Every place who gives me money for code requires comments(Javadoc).... who knew.
    -Search keywords "Java conventions"

    Your program really lacks depth to be a great example, but there are a couple things to mention. (not an attack on you or your code, just the project itself)
    There is no protection against bad input. If I was to run your program, and press cancel when the popup asks "How many stocks have been purchased?", the program would (should) crash with a null pointer exception.
    You have some variables you don't necessarily need, for example:
    comTotal = paid * comPercent;
    formatter.format(comTotal)
    will give the same result as:
    formatter.format(paid * comPercent)
    Having brought that up, let me battle from the other side of this road also... I just told you to use formatter.format(paid * comPercent) in place of the variable comTotal. Now I am going to tell you don't do that.
    If I am reading over code and i see a line that says formatter.format(paid * comPercent) I have to figure out what paid is and what comPercent is and why they are being multiplied together before being formatted. On the other hand seeing the line formatter.format(comTotal) I can get a better understanding of what is going on without looking up two variables and deciding what the math operation is doing to them and why.

    Why did I tell you to do it, then not to do it?
    Many people include far too many unnecessary variables in their code. On the other hand many people try to simplify things (especially in terms of math-in-code) to the point they are no longer simple. There is a happy medium along the way that keeps the code clean and readable but not too crazy toward either extreme.

    The program is not bad at all. This will explain a little more about why I said the program lacks depth.
    There is no requirement to create a Stock object, or to store the related data, but you should. However, when you are getting used to the use of a variable, one can not require you to have objects with data and methods, and methods with parameters returning values. It is too much at one time. Which is why starter projects lack depth. But for the main method you have, nice work. As you learn to use objects, methods, multiple classes etc.. rewrite this program over and over. Every time you learn a new technique that you can apply to this program, do it. But don't modify the old. Rewrite the program from scratch using your new mind. Keep the old copies and you will have a record to watch the program over time. It is actually great practice to rewrite a program from scratch. First, it is good to go through the development process many times and a short program allows you to go through every step but not bang your head on one step for months. Second the more familiar you become with your program (what better way than from start to finish each time), the easier it is to apply new programming techniques to a program you fully understand than trying to learn a new technique on a program you may or may not understand yet.

    Ok too much to read. Good luck

Similar Threads

  1. Simple question
    By Senovit in forum Java Theory & Questions
    Replies: 2
    Last Post: September 16th, 2012, 07:09 PM
  2. Simple I/O Question...well could be simple for you?
    By basketball8533 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: September 30th, 2011, 06:44 AM
  3. Simple question
    By white97 in forum Java Theory & Questions
    Replies: 1
    Last Post: August 11th, 2011, 06:30 PM
  4. Help with a simple question
    By allea in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 28th, 2011, 07:46 AM
  5. not so simple, simple swing question box
    By wolfgar in forum AWT / Java Swing
    Replies: 2
    Last Post: November 20th, 2009, 03:47 AM