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

Thread: Code is not printing how I want it to

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    45
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Code is not printing how I want it to

    Hello, I have the following code that I need help in:

    import java.io.File;
    import java.io.IOException;
    import java.math.BigDecimal;
    import java.math.BigInteger;
    import java.math.RoundingMode;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Scanner;
     
    public class StockPrice {
        static String s = "";
        /**
         * No java docs
         */
        private static final int NUMBER_NEGATIVE_100 = -100;
        /**
         * No java docs
         */
        private static final int NUMBER_6 = 6;
        /**
         * No java docs
         */
        private static final int NUMBER_5 = 5;
        /**
         * No java docs
         */
        private static final int NUMBER_4 = 4;
        /**
         * No java docs
         */
        private static final int NUMBER_3 = 3;
        /**
         * No java docs
         */
        private static final int NUMBER_2 = 2;
        /**
         * No java docs
         */
        private static final int NUMBER_1 = 1;
        /**
         * No java docs
         */
        private static final int NUMBER_0 = 0;
     
        static class Entry {
            public final ArrayList<Date> date = new ArrayList<Date>();
            public final ArrayList<BigDecimal> open = new ArrayList<BigDecimal>();
            public final ArrayList<BigDecimal> high = new ArrayList<BigDecimal>();
            public final ArrayList<BigDecimal> low = new ArrayList<BigDecimal>();
            public final ArrayList<BigDecimal> close = new ArrayList<BigDecimal>();
            public final ArrayList<BigInteger> volume = new ArrayList<BigInteger>();
            public final ArrayList<BigDecimal> adjclose = new ArrayList<BigDecimal>();
     
            public void addEntry(final Date nDate, final BigDecimal nOpen,
                    final BigDecimal nHigh, final BigDecimal nLow,
                    final BigDecimal nClose, final BigInteger nVolume,
                    final BigDecimal nAdjclose) {
                Date dateVariable;
                BigDecimal openVariable;
                BigDecimal highVariable;
                BigDecimal lowVariable;
                BigDecimal closeVariable;
                BigInteger volumeVariable;
                BigDecimal adjcloseVariable;
     
                dateVariable = nDate;
                openVariable = nOpen;
                highVariable = nHigh;
                lowVariable = nLow;
                closeVariable = nClose;
                volumeVariable = nVolume;
                adjcloseVariable = nAdjclose;
     
                date.add(dateVariable);
                open.add(openVariable);
                high.add(highVariable);
                low.add(lowVariable);
                close.add(closeVariable);
                volume.add(volumeVariable);
                adjclose.add(adjcloseVariable);
     
            }
     
            public boolean getTest(final String n) throws ParseException {
                final int length1 = this.date.size();
                boolean truefalse = false;
     
                for (int a = NUMBER_0; a < length1; a++) {
                    final SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy");
                    final Date dateString = df.parse(n);
     
                    if ((dateString.compareTo(date.get(a))) == NUMBER_0) {
                        truefalse = true;
                        break;
                    }
                }
                return truefalse;
            }
     
            public int position(final String n) throws ParseException {
                final int length1 = this.date.size();
                int index = NUMBER_0;
                for (int a = NUMBER_0; a < length1; a++) {
     
                    final SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy");
                    final Date dateString = df.parse(n);
     
                    if ((dateString.compareTo(date.get(a))) == NUMBER_0) {
                        index = a;
                        break;
                    }
                }
                return index;
            }
     
            public String average(final int a, final int b) {
                final int total = (a - b) + NUMBER_1;
     
                final Double overavgDouble = 0.0;
                final Double highavgDouble = 0.0;
                final Double lowavgDouble = 0.0;
                final Double closeavgDouble = 0.0;
                final int volumeavgInteger = NUMBER_0;
                final Double adjcloseavgDouble = 0.0;
     
                BigDecimal openavg = new BigDecimal(overavgDouble);
                BigDecimal highavg = new BigDecimal(highavgDouble);
                BigDecimal lowavg = new BigDecimal(lowavgDouble);
                BigDecimal closeavg = new BigDecimal(closeavgDouble);
                BigInteger volumeavg = BigInteger.valueOf(volumeavgInteger);
                BigDecimal adjcloseavg = new BigDecimal(adjcloseavgDouble);
     
                for (int c = b; c <= a; c++) {
                    openavg = openavg.add(this.open.get(c));
                    highavg = highavg.add(this.high.get(c));
                    lowavg = lowavg.add(this.low.get(c));
                    closeavg = closeavg.add(this.close.get(c));
                    volumeavg = volumeavg.add(this.volume.get(c));
                    adjcloseavg = adjcloseavg.add(this.adjclose.get(c));
                }
                final BigDecimal total1 = new BigDecimal(total);
                final BigInteger total2 = BigInteger.valueOf(total);
     
                openavg = openavg.divide(total1, NUMBER_2, RoundingMode.HALF_UP);
     
                highavg = highavg.divide(total1, NUMBER_2, RoundingMode.HALF_UP);
     
                lowavg = lowavg.divide(total1, NUMBER_2, RoundingMode.HALF_UP);
     
                closeavg = closeavg.divide(total1, NUMBER_2, RoundingMode.HALF_UP);
     
                volumeavg = volumeavg.divide(total2);
     
                adjcloseavg = adjcloseavg.divide(total1, NUMBER_2,
                        RoundingMode.HALF_UP);
     
                final String average = openavg.toString() + ","
                        + highavg.toString() + "," + lowavg.toString() + ","
                        + closeavg.toString() + "," + volumeavg.toString() + ","
                        + adjcloseavg.toString();
                return average;
            }
     
            public String sString(String s) {
                String tempString = "";
                tempString =   tempString + "\n" + s;
     
                return tempString;
            }
     
        }
     
     
     
     
        public static void main(final String[] args) throws IOException,
                ParseException {
     
     
            String s1 = "";
            final Scanner input = new Scanner(new File("DJIA.csv"));
            Date d;
            BigDecimal open1;
            BigDecimal high1;
            BigDecimal low1;
            BigDecimal close1;
            BigInteger volume1;
            BigDecimal adjclose1;
     
            final Entry entry = new Entry();
     
            input.nextLine();
     
            while (input.hasNext()) {
     
                final String first = input.nextLine();
                final String[] split = first.split(",");
     
                final Calendar cal = Calendar.getInstance();
                cal.add(Calendar.YEAR, NUMBER_NEGATIVE_100);
     
                final SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy");
     
                df.set2DigitYearStart(cal.getTime());
     
                d = df.parse(split[NUMBER_0]);
     
                open1 = new BigDecimal(split[NUMBER_1]);
     
                high1 = new BigDecimal(split[NUMBER_2]);
     
                low1 = new BigDecimal(split[NUMBER_3]);
     
                close1 = new BigDecimal(split[NUMBER_4]);
     
                volume1 = new BigInteger(split[NUMBER_5]);
     
                adjclose1 = new BigDecimal(split[NUMBER_6]);
     
                entry.addEntry(d, open1, high1, low1, close1, volume1, adjclose1);
     
            }
     
            final Scanner stdInput = new Scanner(System.in);
     
     
     
            int a = NUMBER_0;
            int b = NUMBER_0;
     
     
            while (stdInput.hasNext ()) {
                 String getLine = stdInput.nextLine();
                final String[] divide = getLine.split(" ");
                final String first = divide[NUMBER_0].toString();
                final String second = divide[NUMBER_1].toString();
                boolean temp1 = false;
                boolean temp2 = false;
     
                temp1 = entry.getTest(first);
                temp2 = entry.getTest(second);
     
                if (temp1 && temp2) {
                    a = entry.position(first);
                    b = entry.position(second);
     
                    final String output = entry.average(a, b);
     
                    s = entry.sString(output);
     
                } else {
                    s1 = "No Data";
                    s = entry.sString(s1);
     
                }
     
     
     
            }
     
     
       System.out.print(s);
        }
     
    }

    First, my code is not printing how i want it to. I want to let the user type in five different inputs, each on a new line, and then when they press "Ctrl c" in the command prompt, the results will display for these five different inputs, each on a new line. This has been giving me problems a long time. And yes, this is my code and I made it in eclipse.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Code is not printing how I want it to

    my code is not printing how i want it to
    Please post the code's output, add some comments that explain what is wrong with the output and post what you want the output to look like.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2012
    Posts
    45
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code is not printing how I want it to

    I did, but someone deleted my original post... And i spent 20 minutes making it.. Bummer!

    --- Update ---

    I'll start over again

    --- Update ---

    OK, here is an assignment that I already turned it. It's already graded, but I don't understand it. We are studying objects. This is my second semester in java. I do not understand the concepts of objects. I know there are three different types of objects. I get that. The program I made, you can create it using normal return methods and print statements, but the instructor wants us to use objects. To do this, he said to make another class within the main class. My questions are:

    (1) To make the second class within the first, does the second one have to be static. IE "static class Example". I get that to call this class, you have to say Example.**** . But he was explaining that I would have to create a new instance of this object. I.E. "Example *** = new Example() " . Why is that? Please explain. Then after creating that, I can call the object Example.*** to calculate the different problems in my program. Also, why are some objects return objects and others not. Wouldn't these return objects be a return method??? What makes it an object then? Even for some void objects, there is a return statement. Last, I need to use the toString() object (is it a method), but I need it to work for my program. I can't get it to work for my program.

    Here is the assignment:

    Data Structure
     
    A data structure is a class that holds fields of various type as a whole structure. Then this class can be use as a single entity, i.e. in ArrayList. There are different methods to create data structure, but the one that we prefer here has this properties:
     
        All fields should be final
        value of the fields should be pass/set using one of the constructors
        no set method
     
    This is an example:
     
    public final class MyPoint {
        public final double x, y;
     
        public MyPoint (final int p_x, final int p_y) {
            x = p_x;
            y = p_y;
        }
     
        public MyPoint (final int p_x) {
            this(p_x, 0);
        }
    }
     
    Task
     
    Your task is exercise 3.2.31 of the text book. You need to read data file (DJIA.csv) and store each of the records into a data type called Entry. To store all records in memory, use an ArrayList of your entries. The task is to find the average of all quantities (Open, High, Low, Close, Volume, Adj. Close) over various periods of time. The first entry on each record is the date. Read two dates from the standard input stream, compute the average of all the data between the two dates, and print them to the standard output stream. Repeat this task for every pair of dates in the input.
     
    To create a new inner class use this template:
     
    public final class StockPrice {
     
        static class Entry {
            public final ...;
            ... 
            public Entry (...) {
                ...
            }
        }
     
        public static void main (String[] args) {
            ...
        }
    }   
     
    You need to read dates from the input stream and store them in a Date object. Use SimpleDateFormat to parse a string of date. Because all of the dates are in the past, we set the 2 digit year start to 100 years before the current time. This is a simple code to do so:
     
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, -100);
    final SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy");
    ...
    df.set2DigitYearStart(cal.getTime());
    ...
    final Date d = df.parse( your_string );
    ...
     
     
    The only difference of this task with your previous tasks is reading data from a file. To do so, simply create a Scanner object by passing a File object instead of system.in. You need to take care of the IOException that can be occur during creating of Scanner object with a File object. This is a sample code to do so:
     
        public static void main(final String[] args) throws IOException, ParseException {
     
          final Scanner input = new Scanner( new File ("Filename") );
          ...
    }
     
    The argument of the program should be the data filename. On standard input, each pair of dates should use for computing the averages. be aware that first seven tokens in the data file are the name of the column and you should skip them in your programs (read them, but do not store them). please take a look at sample input and output and write your program with the same format of IO.
     
    Sample Input:
    command: java StockPrice DJIA.csv
    standard input:
    16-Mar-06 17-Mar-06
    15-Mar-06 17-Mar-06
    12-Mar-28 15-Mar-28
    29-Feb-44 12-May-71
     
     
    Sample Output:
    11252.96,11309.87,11214.65,11266.45,2420899968.00,11266.45
    11218.56,11292.67,11175.51,11247.55,2378266624.00,11247.55
    No Data
    511.32,515.08,507.81,511.42,4215199.18,511.42
     
     
    Notes: 
     
        use BigDecimal for all numbers
        round numbers to two digits after decimal points (use scale 2 and ROUND_HALF_UP, see BigDecimal documentation of divide command)
        Dates may not be in order in DJIA.cvs but on the input first date will be always before second date
        use instance method compareTo of the Date class to compare dates. see API documentation.
        if no data avalable for specified range or the range is wrong, write "No Data" on the output.
        use static inner classes (for Entry) to construct your data type
        Notes on Static vs Instance.

    Even when I'm typing this:
    16-Mar-06 17-Mar-06
    15-Mar-06 17-Mar-06
    12-Mar-28 15-Mar-28
    29-Feb-44 12-May-71

    I'm only getting the last input printed out. I know it seems like an easy fix, but I have spent over 6 hours trying to figure it out. Also, how do I convert this program and make it more object oriented. My "GetTest" object(or method) and the print object looks like methods to me. I need to make this object.

    Last, concerning the print object, I need to use the toString() built in object to print my inputs. The way I want to do this is that in the command prompt, the user types in the inputs, each on a new line. Only after he ends the program and presses "Ctrl c", then will the output print, each on a new line. This is similar to the assignment. In my program. only the last input is printing.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Code is not printing how I want it to

    To make the second class within the first,
    See the tutorial: Nested Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

    there are three different types of objects
    Can you list the different types? I'm not sure I understand what you mean.

    why are some objects return objects and others not.
    Same question. What do you mean here?

    I'm only getting the last input printed out
    Can you copy the full contents of the console window from when you execute the program and paste it here.
    Add some comments where the program didn't do what you wanted.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Sep 2012
    Posts
    45
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code is not printing how I want it to

    I have just corrected the program to the one I submitted for my assignment. This was made in eclipse, and checkstyle was used. And the instructor wants everything to be final, all the numbers to be refractored (extract constant), etc. Here is the output of my program:

     
    C:\Users\Red Bull\Documents\Documents\School\Programming\Programs>java StockPrice DJIA.csv
    16-Mar-06 17-Mar-06
    15-Mar-06 17-Mar-06
    12-Mar-28 15-Mar-28
    29-Feb-44 12-May-71
     
    511.32,515.08,507.81,511.42,4215199,511.42
    C:\Users\Red Bull\Documents\Documents\School\Programming\Programs>

    See, it's only printing the last output.

    So my questions are:
    (1) What are objects (explain in details), and how do I create them, initialize them, and how do these differ from methods. Also, while creating a class within a class, how was the instructor able to do this:
    public final class MyPoint {
        public final double x, y;
     
        public MyPoint (final int p_x, final int p_y) {
            x = p_x;
            y = p_y;
        }
     
        public MyPoint (final int p_x) {
            this(p_x, 0);
        }
    }

    (2) how do I use the built in toString() object, and how do I call it. I need to use this to print my output. But I don't know how to create it
    (3) How do I make my program more object oriented. Except for the "entry" object, the rest are methods
    (4) How do I print all outputs, and not just the last, when the user presses "Ctrl c" in the command prompt.
    (5) Are there any easier ways to create my program, while still fulfilling the assignment requirements (BigDecimal, BigInteger, toString() object, using objects, having classes within classes, etc)

    I'm lost

    --- Update ---

    if someone can modify my program and make it more object oriented, I would appreciate it. Please explain how to initialize objects very detailed for me. I have read all the articles online and I am still confused. The three different objects I was talking about incorporation, instance of, and inheritence. Please explain each. What is an instance of. I get that for every object that you create, you have to make an instance of it. And what does incorporating an object means.

    In one object, I believe it said "public ** {return **}". How is it returning something if it's not static? I say another one where it is "public void ** {return **}". Once again, if it's a void object, how is it returning something. Last, for the toString() object, the syntax is "public String toString()". Wouldn't this be a method, and not an object? And where does this "object" need to be placed in the program? Within the main class, the object class, the main program, where?

    EXPLAIN PLEASE

    --- Update ---

    If you don't understand my answer, don't ignore it, ask a question.

    I do not understand it Norm. And where is everyone at? Saturday night partying?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Code is not printing how I want it to

    Dinner time here. Be back in an hour.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Sep 2012
    Posts
    45
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code is not printing how I want it to

    Quote Originally Posted by Norm View Post
    Dinner time here. Be back in an hour.
    ok I would appreciate all the help and explaining that I can get

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Code is not printing how I want it to

    What are objects
    Try google. That's a huge topic way past what anyone can answer here.
    how do I use the built in toString() object
    Here is a basic misunderstanding that will make it hard for anyone to communicate with you about OOP.
    toString() is a method not an object.

    See the tutorial: The Really Big Index
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 1
    Last Post: September 28th, 2011, 07:29 AM
  2. Help in printing trees
    By cool_97 in forum What's Wrong With My Code?
    Replies: 18
    Last Post: July 23rd, 2011, 04:46 PM
  3. 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
  4. [SOLVED] Printing Array without printing empty elements
    By CarlMartin10 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 12th, 2010, 02:41 AM
  5. Code not printing correctly
    By Movies32 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 6th, 2010, 03:59 PM

Tags for this Thread