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

Thread: Starting Out With Java Programming Challenge Chapter 10 #11

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Starting Out With Java Programming Challenge Chapter 10 #11

    public static double getWeeklySales(String str)
    {
    double weekTotal = 0.0;

    // Create the tokenizer.
    StringTokenizer strtok = new StringTokenizer(str, ",");
    // Accumulate the value of the tokens.
    while (strtok.hasMoreTokens())
    {
    weekTotal =+ Double.parseDouble(str);
    }

    return weekTotal;
    }

    }
    Exception in thread "main" java.lang.NumberFormatException: For input string: "1245.67,1490.07,1679.87,2371.46,1783.92,1461.99,2 059.77"
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at SalesAnalysis.getWeeklySales(SalesAnalysis.java:10 9)
    at SalesAnalysis.main(SalesAnalysis.java:61)


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Welcome! Please read this topic to learn how to post code correctly and other useful info for new members.

    Post your code correctly, describe what you need help with and/or ask a question.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Exception in thread "main" java.lang.NumberFormatException: For input string: "1245.67,1490.07,1679.87,2371.46,1783.92,1461. 99,2 059.77"
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at SalesAnalysis.getWeeklySales(SalesAnalysis.java:10 9)
    The code at line 109 used an invalid String in the call to the parseDouble() method. Check the code to see what String should be used.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Quote Originally Posted by Norm View Post
    The code at line 109 used an invalid String in the call to the parseDouble() method. Check the code to see what String should be used.
    public static double getWeeklySales(String str)
    {
    double weekTotal = 0.0;

    // Create the tokenizer.
    StringTokenizer strtok = new StringTokenizer(str, ",");
    // Accumulate the value of the tokens.
    while (strtok.hasMoreTokens())
    {
    weekTotal =+ Double.parseDouble(str);
    }

    return weekTotal;
    }
    the error I am getting is with the "Double.parseDouble(str)"

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    The contents of the variable: str is NOT parseable to a double. str contains many values each of which can be parsed.
    The StringTokenizer class separates out the parts of str that can be parsed. Use the tokens that the StringTokenizer class obtains from str. Read the API doc for StringTokenizer to see what method to use.

    When posting code be sure to wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Quote Originally Posted by Norm View Post
    The contents of the variable: str is NOT parseable to a double. str contains many values each of which can be parsed.
    The StringTokenizer class separates out the parts of str that can be parsed. Use the tokens that the StringTokenizer class obtains from str. Read the API doc for StringTokenizer to see what method to use.

    When posting code be sure to wrap your code with code tags:
    I have rewritten my "getWeeklySales" class but the output is not correct but I am no longer getting a run time exception.
     public static double getWeeklySales(String str)
       {
          double weekTotal = 0.0;
     
          // Create the tokenizer.
          StringTokenizer strtok = new StringTokenizer(str, ",");
         // Accumulate the value of the tokens.
     
             while (strtok.hasMoreTokens())
          {
              weekTotal =+ Double.parseDouble(strtok.nextToken());
          }
     
          return weekTotal;
       }

    The "tokens" should be coming from the first line across from a .txt file
    Last edited by Norm; March 3rd, 2014 at 12:00 PM. Reason: removed noparse tags

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    the output is not correct
    Please explain. Post the current output and the expected output.

    Try debugging the code by adding println() statements that print out the tokens that are returned by nextToken() so you can see what is being added to the total.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    public class SalesAnalysis
    {
     
       public static void main(String[] args) throws IOException
       {
          // To hold a line from the file
           String line;
          // Accumulator for all weeks
           double totalWeeks = 0;
          // Average weekly sales
           double weeklyAverage ;
          // Total sales for a week
           double weeklyTotal =0;
          // Highest sales
           double highestSales;
          // Lowest sales
           double lowestSales;
          // Week # with highest sales
           int highWeek =0;
          // Week # with lowest sales
           int lowWeek=0;
          // The week number;
           int weekNumber = 0;          
          // Create a DecimalFormat object to format dollar amounts.
          DecimalFormat dollar = new DecimalFormat("$#,##0.00");
     
          // Open the SalesData.txt file.
          File file = new File("SalesData.txt");
          Scanner inputFile = new Scanner(file);
     
          // Process the file contents.
          while (inputFile.hasNext())
          {
               // Read a line from the file.
              line = inputFile.nextLine();
              // Increment the week counter.
              weekNumber ++;
              // Get the total sales for this week.
              getWeeklySales(line);
     
              weeklyTotal= getWeeklySales(line);
     
               // Calculate the average weekly sales.
                weeklyAverage = weeklyTotal/line.length();
               // Display the total and average for the week. 
              System.out.println("Week #" + weekNumber + " sales: " + weeklyTotal+
             "    Average daily sales for Week #" + weekNumber+": " + weeklyAverage);
          }
         // Accumulate the weekly sales.
          for (int i=0; i<=weekNumber;i++)
          {
          totalWeeks +=weeklyTotal; 
        // Find the highest and lowest so far.
          if (totalWeeks > weeklyTotal)
          highWeek = weekNumber;
          else
          lowWeek = weekNumber;
          }
          // Close the file
           inputFile.close();
     
       // Display the remaining results.
        System.out.println("Total sales for all weeks: " + totalWeeks +"\n"+ 
        "Average weekly sales: "+ totalWeeks/3 + "\n"+ "The highest sales were "
        + "during week #"+ highWeek+"\n"+"The lowest sales were made during week #"
        + lowWeek);
     
         }
     
       /**
          The getWeeklySales method accepts a string containing a
          list of sales for the week, with each day's sales 
          separated by commas. It tokenizes the string, totals
          the numbers, and returns the total sales for the week.
          @param str The string containing the list of sales.
          @return The total of the sales.
       */
     
       public static double getWeeklySales(String str)
       {
          double weekTotal = 0.0;
     
          // Create the tokenizer.
          StringTokenizer strtok = new StringTokenizer(str, ",");
         // Accumulate the value of the tokens.
     
             while (strtok.hasMoreTokens())
          {
              weekTotal =+ Double.parseDouble(strtok.nextToken());
          }
     
          return weekTotal;
       }
     
    }
    Current output:
    Week #1 sales: 2059.77 Average daily sales for Week #1: 37.45036363636363
    Week #2 sales: 1469.36 Average daily sales for Week #2: 26.71563636363636
    Week #3 sales: 1128.36 Average daily sales for Week #3: 20.51563636363636
    Total sales for all weeks: 4513.44
    Average weekly sales: 1504.4799999999998
    The highest sales were during week #3
    The lowest sales were made during week #3
    Expected output:
    Week #1 sales:12,092.75 Average daily sales for week #1: $1,727.54
    Week #2 sales:27,461.00 Average daily sales for week #2: $3,923.00
    Week #3 sales:12,058.34 Average daily sales for week #3: $1,722.62
    Total sales for weeks: $51,612.09
    Average weekly sales: $17,204.03
    The highest sales were made during week #2.
    The lowest sales were made during week #3.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Where is the debug println()s output that shows what values were read and used in computing the total?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Quote Originally Posted by Norm View Post
    Where is the debug println()s output that shows what values were read and used in computing the total?
    I tried implementing this code in the while loop of the "getWeekly Sales" method and a run time exception was thrown:
    System.out.println(strtok.nextToken());

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    The problem with that code is that the token is only printed and then not used for the total.
    The code needs to:
    assign the token to a String,
    print the String
    parse the String to a double
    and add the double to the total
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    Ok I reentered this code in the first while loop and realized that the code is skipping the first two lines in the .txt file that I am receiving the data from but I don't understand why it is skipping
      StringTokenizer strtok = new StringTokenizer(line, ",");
         // Accumulate the value of the tokens.
     
             while (strtok.hasMoreTokens())
             {
                 System.out.println(strtok.nextToken());
             }

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    What is printed by the code in post#12? Are there items on a line that are not printed?
    Add a println() to print the contents of the variable: line so you can see the full text of the line as well as the tokens that the StringTokener gets.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

    after looking at my code 3 time I realized how stupid I am I use the "=+" operator instead of "+=" that is why it wasn't accumulating correctly.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Starting Out With Java Programming Challenge Chapter 10 #11

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

  16. The Following User Says Thank You to Norm For This Useful Post:

    StrangeFruit (March 3rd, 2014)

Similar Threads

  1. Replies: 8
    Last Post: February 12th, 2013, 05:45 AM
  2. Fundamental knowledge before starting Java programming.
    By wsung in forum Java Theory & Questions
    Replies: 1
    Last Post: October 7th, 2012, 05:42 AM
  3. Programming challenge
    By pierce21 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 26th, 2012, 07:29 AM
  4. New to Programming, Starting college for computer engineering
    By TheBLC84 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 17th, 2010, 04:06 AM
  5. Starting a java programming career
    By oss_2008 in forum The Cafe
    Replies: 3
    Last Post: July 8th, 2009, 07:45 AM

Tags for this Thread