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 4 of 4

Thread: Beginner/Intermediate Java Code - NullPointerException and wrong output.

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Beginner/Intermediate Java Code - NullPointerException and wrong output.

    First off, this IS a homework assignment I have been working on.
    I believe I'm close to finishing but can't seem to figure out this small bit.

    The input:
    buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200 share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at $25 each;sell 200 share(s) at $35 each;
    The output should be $1070 (using FIFO protocol).

    I can see the problem being something to do with my sell() method when trying to perform Stocklist.peek()...

    I've tried different variations of code and seem to be stuck..

    Any hints/help would be greatly appreciated.

    import java.util.*;
    import java.text.*;
     
    public class Stocks {
     
        private int shares;
        private int price;
        private int temp;
        private int finalPrice;
        private int finalShares;
        private static int total;
        private Queue<Stocks> StockList = new LinkedList<Stocks>();
     
        private static NumberFormat nf = NumberFormat.getCurrencyInstance();
     
        public Stocks()
        {
            shares      = 0;
            price       = 0;
     
        }
     
        public Stocks(int shares, int price)
        {
            this.shares     = shares;
            this.price      = price;
        }
     
        public int getShares()
        {
            return this.shares;
        }
     
        public int getPrice()
        {
            return this.price;
        }
     
        public void setShares(int shares)
        {
            this.shares = shares;
        }
     
        public void setPrice(int price)
        {
            this.price = price;
        }    
     
        public void sell() {
            int sharesToSell = this.getShares();
            int priceToSell = this.getPrice();
     
            while (!StockList.isEmpty() == false) { // **Something wrong starting here.
     
                 int numShares = StockList.peek().getShares(); // **Throws NullPointerException
                 int sharePrice = StockList.peek().getPrice();
     
                while (numShares < sharesToSell || numShares == sharesToSell) {
                    temp = sharesToSell - numShares; // Remaining shares to sell
                    finalShares = sharesToSell - temp; // # Shares selling at price
                    finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price                
                    total += (finalPrice * finalShares); // Calculates total
                    System.out.println(total);
     
                } sharesToSell = temp;
     
                if (numShares > sharesToSell) {
                    temp = numShares - sharesToSell; // Remaining shares that were bought
                    finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
                    total += (finalPrice * sharesToSell); // Adds to running total
                    StockList.peek().setShares(temp);
     
                }
            }
        }
     
        public void buy() { 
            int numShares = this.getShares();
            int priceToBuy = this.getPrice();
     
            Stocks newStock = new Stocks(numShares,priceToBuy);
            StockList.add(newStock); // adds stock to list
     
            total += (numShares * priceToBuy);
        }
     
        public static int getTotal() { // gets total profit (or loss)
            return total;
        }
     
        // *****MAIN METHOD*****
        public static void main(String[] args){
     
     
            Scanner scan = new Scanner(System.in);
     
            System.out.println("Enter transaction sequence:");
     
            String input = scan.nextLine().trim();
            String[] inputArray = new String[50];
            String[] inputArray2 = new String[50];
            String[] inputArray3 = new String[50];
            int numShares, sharePrice;
     
            inputArray = input.split(";"); // Splits input at ";"
                                          // and enters into inputArray
            for (String i : inputArray) { // Checks for BUY or SELL
                if (i.toUpperCase().contains("BUY")) { 
                    inputArray2 = i.split(" ");
                    inputArray2[4] = inputArray2[4].substring(1); // Removes $ sign
     
                    try {
                        numShares = Integer.parseInt(inputArray2[1]);
                        sharePrice = Integer.parseInt(inputArray2[4]);
     
                        Stocks newStock = new Stocks(numShares,sharePrice);
                        newStock.buy();
     
                    } catch (NumberFormatException e) {
                        System.out.println("Number Format Error");
                        return;
                    }
     
                }
     
                else if (i.toUpperCase().contains("SELL")) {
                    inputArray3 = i.split(" ");
                    inputArray3[4] = inputArray3[4].substring(1);
     
                    try {
                        numShares = Integer.parseInt(inputArray3[1]);
                        sharePrice = Integer.parseInt(inputArray3[4]);
     
                        Stocks newStock = new Stocks(numShares,sharePrice);
                        newStock.sell(); // **Must be problem with sell() method.
     
                    } catch (NumberFormatException e) {
                        System.out.println("Number Format Error");
                        return;
                    }
                } else {
                    System.out.println("An error has been found.");
                }
            } 
            System.out.println();
            System.out.println("Total:"+nf.format(getTotal()));
        }
    }


  2. #2
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Beginner/Intermediate Java Code - NullPointerException and wrong output.

    int numShares = StockList.peek().getShares();
    Most probably, this StockList.peek() is returning a null and you want a null to call getShares(). That is actually the problem. Good Luck

  3. The Following User Says Thank You to Mr.777 For This Useful Post:

    tt52 (October 19th, 2011)

  4. #3
    Junior Member
    Join Date
    Oct 2011
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Beginner/Intermediate Java Code - NullPointerException and wrong output.

    I think what I'm not understanding is why the the StockList.peek() returns null?

    Shouldn't the list contain Stocks from the buy() method?

  5. #4
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Beginner/Intermediate Java Code - NullPointerException and wrong output.

    Quote Originally Posted by tt52 View Post
    I think what I'm not understanding is why the the StockList.peek() returns null?

    Shouldn't the list contain Stocks from the buy() method?
    Did you try debugging your program?
    If you don't know debugging, place print statements to find the value of your queue(list) at different locations.

Similar Threads

  1. Beginner trying to write Java code, has issue w/ printing result and 2 decimals
    By flpanthers1 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 5th, 2011, 11:11 AM
  2. Replies: 3
    Last Post: March 8th, 2011, 07:44 AM
  3. Very beginner - What's wrong in my applet declaration?
    By rforte in forum What's Wrong With My Code?
    Replies: 5
    Last Post: April 30th, 2010, 04:54 AM
  4. [SOLVED] what is wrong for the java code
    By chuikingman in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 11th, 2010, 02:00 AM
  5. i'm new to java. whats is wrong in this code?
    By igorek83 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 30th, 2009, 08:38 PM

Tags for this Thread