Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Why isn't my float total updating?

    Okay, so my text book's directions say, "Before the while loop, declare a total variable of the float type. After the code that displays the line item, use the compound addition operator to add the total for the line item to the total variable. After the while loop, display the total."

    Here's my code so far, which for some reason won't change the initial 0.0 value for the total variable:
    Java Code:
    package murach.ui;
    
    import java.util.Scanner;
    import java.lang.Math;
    
    import murach.db.ProductDB;
    import murach.business.LineItem;
    import murach.business.Product;
    
    public class LineItemApp {
    
        public static void main(String args[]) {
            // display a welcome message
            System.out.println("Welcome to the Line Item Calculator");
            System.out.println();
    
            // create 1 or more line items
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            float total = 0;
            byte counter = 0;
            while (choice.equalsIgnoreCase("y")) {
                // get input from user
                System.out.print("Enter product code: ");
                String productCode = sc.nextLine();
    
                System.out.print("Enter quantity:     ");
                int quantity = Integer.parseInt(sc.nextLine());
                
                // get the Product object
                Product product = ProductDB.getProduct(productCode);
    
                // create the LineItem object
                LineItem lineItem = new LineItem(product, quantity);
    
                // display the output
                String message = "\nLINE ITEM\n" +
                    "Code:        " + product.getCode() + "\n" +
                    "Description: " + product.getDescription() + "\n" +
                    "Price:       " + product.getPriceFormatted() + "\n" +
                    "Quantity:    " + lineItem.getQuantity() + "\n" +
                    "Total:       " + lineItem.getTotalFormatted() + "\n";
                System.out.println(message);
                counter++;
                total += total;
                System.out.println("New total: " + total);
    
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.nextLine();
                System.out.println();
            }
            sc.close();
            System.out.println("Number of line items: " + counter);
            System.out.println("Invoice total: " + total);
            System.out.println("Bye!");
        }
    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why isn't my float total updating?

    Java Code:
    total += total;
    You're adding total to itself, and since it starts as zero it will never change.

    According to the requirements you should be adding the line item's total to the total.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    The instructions for the next exercise say, "After displaying the line item, use the max and min and min methods of the Math class to update the values for the largest and smallest line items. To get this to work correctly, you need to initialize the minimum value to a very large value. Also, within the min and max methos of the Math class, you need to cast the value that's returned by the getTotal method of the LineItem class to a float value."

    I've got a good start, but I'm stumped on what the logic should be for checking if the current lineItem's total exceeds the max or min. Here's my code so far:
    Java Code:
    package murach.ui;
    
    import java.util.Scanner;
    import java.lang.Math;
    
    import murach.db.ProductDB;
    import murach.business.LineItem;
    import murach.business.Product;
    
    public class LineItemApp {
    
        public static void main(String args[]) {
            // display a welcome message
            System.out.println("Welcome to the Line Item Calculator");
            System.out.println();
    
            // create 1 or more line items
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            float total = 0;
            byte counter = 0;
            float largestLineItem; 
            float smallestLineItem = (float)54.50;//initialized to the value the cheapest item      
            while (choice.equalsIgnoreCase("y")) {
                // get input from user
                System.out.print("Enter product code: ");
                String productCode = sc.nextLine();
    
                System.out.print("Enter quantity:     ");
                int quantity = Integer.parseInt(sc.nextLine());
                
                // get the Product object
                Product product = ProductDB.getProduct(productCode);
    
                // create the LineItem object
                LineItem lineItem = new LineItem(product, quantity);
    
                // display the output
                String message = "\nLINE ITEM\n" +
                    "Code:        " + product.getCode() + "\n" +
                    "Description: " + product.getDescription() + "\n" +
                    "Price:       " + product.getPriceFormatted() + "\n" +
                    "Quantity:    " + lineItem.getQuantity() + "\n" +
                    "Total:       " + lineItem.getTotalFormatted() + "\n";
                System.out.println(message);
                counter++;
                total += lineItem.getTotal();
                System.out.println("New total: " + total);//current line item finished being displayed
                //Use the min and max methods of the Math class to update the values for the largest
                //and smallest line items:
                if(total > smallestLineItem){
                	//the (total > smallestLineItem) condition technically will only work on the first
                	//while loop iteration, so what's next?
                }
                else if//...help! I'm stuck here. What's the logic that should be used?
    
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.nextLine();
                System.out.println();
            }
            sc.close();
            System.out.println("Number of line items: " + counter);
            System.out.println("Invoice total: " + total);
            System.out.println("Bye!");
            /*
             int x = 67;
             int y = 23;
             int max = Math.max(x, y);//max is 67
             int min = Math.min(x, y);//min is 23
             */
        }
    }

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why isn't my float total updating?

    Java Code:
    float smallestLineItem = (float)54.50;//initialized to the value the cheapest item
    The requirements suggest initialising this to a very large value.
    You seem to have initialised it to a small one (cheapest item).

    You then need to check each line item cost (not the total cost) against this smallestLineItem and if it's less then assign that new value to smallestLineItem.
    There is no else.

    You do the opposite for largestLineItem. You should initialise it to 0, and assign a line item cost to it if the cost is greater.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by Tolls View Post
    The requirements suggest initialising this to a very large value.
    You seem to have initialised it to a small one (cheapest item).
    That's because the requirements make no freaking sense to me. Why would it make sense to initialize the smallestLineItem to a very large value when all I have to work with is this:
    Java Code:
    public class ProductDB {
    
        public static Product getProduct(String productCode) {
            // In a more realistic application, this code would
            // get the data for the product from a database
            // For now, this code just uses if/else statements
            // to return the correct product data
    
            // create the Product object
            Product product = new Product();
    
            // fill the Product object with data
            product.setCode(productCode);
            if (productCode.equalsIgnoreCase("java")) {
                product.setDescription("Murach's Java Programming");
                product.setPrice(57.50);
            } else if (productCode.equalsIgnoreCase("jsp")) {
                product.setDescription("Murach's Java Servlets and JSP");
                product.setPrice(56.50);
            } else if (productCode.equalsIgnoreCase("mysql")) {
                product.setDescription("Murach's MySQL");
                product.setPrice(54.50);
            } else {
                product.setDescription("Unknown");
            }
            return product;
        }
    }
    If I initialize the smallest value to a very large value, say 500.50, it would forever be impossible to get a value that would exceed that, since the only possible prices are 54.50, 56.50, and 57.50. That being said, lets recall the part of the directions that said:

    "Also, within the min and max methods of the Math class, you need to cast the value that's returned by the getTotal method of the LineItem class to a float value."

    The code for the getTotal method is as follows:
    Java Code:
    public double getTotal() {
            double total = quantity * product.getPrice();
            return total;
        }
        
        public String getTotalFormatted() {
            double total = this.getTotal();
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            String totalFormatted = currency.format(total);        
            return totalFormatted;
        }
    So help me understand why you're saying this:
    Quote Originally Posted by Tolls View Post
    You then need to check each line item cost (not the total cost) against this smallestLineItem and if it's less then assign that new value to smallestLineItem.
    There is no else.

  6. #6
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Why isn't my float total updating?

    The logic behind initializing the smallest value to a large value is that the first comparison you do, your value always "wins". Try this code and see what happens:
    Java Code:
    public class Smallest {
        public static void main(String[] args) {
    
            int smallest = 0;
            int[] numbers = {14, 56, 32, 43, 75, 23, 65, 34, 45};
            for (int number : numbers) {
                smallest = Math.min(smallest, number);
            }
    
            System.out.println("smallest = " + smallest);
    
        }
    }
    If you run this, you will see the smallest number is still 0, the initialised value. If you change it to: int smallest = Integer.MAX_VALUE; then any of your numbers will ALWAYS be the smallest and after that, the comparison will work as expected.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    If I initialize the smallest value to a very large value, say 500.50, it would forever be impossible to get a value that would exceed that, since the only possible prices are 54.50, 56.50, and 57.50.
    See SurfMan's post.
    The bit in bold is the opposite of what you want to do.
    You want the smallest value, so you want something that is less than the current smallest.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why isn't my float total updating?

    And just in case you didn't know, you can initialize a float as follows:

    float flt = 40.6f;

    No need for a float cast.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    In the following code, it's obvious that the errors on lines 62 and 63 are that variables max and min are out of scope, because they are declared inside the while loop:
    Java Code:
    package murach.ui;
    
    import java.util.Scanner;
    import java.lang.Math;
    
    import murach.db.ProductDB;
    import murach.business.LineItem;
    import murach.business.Product;
    
    public class LineItemApp {
    
        public static void main(String args[]) {
            // display a welcome message
            System.out.println("Welcome to the Line Item Calculator");
            System.out.println();
    
            // create 1 or more line items
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            float total = 0;
            byte counter = 0;
            float largestLineItem = (float)0.0; 
            float smallestLineItem = (float)500.00;     
            while (choice.equalsIgnoreCase("y")) {
                // get input from user
                System.out.print("Enter product code: ");
                String productCode = sc.nextLine();
    
                System.out.print("Enter quantity:     ");
                int quantity = Integer.parseInt(sc.nextLine());
                
                // get the Product object
                Product product = ProductDB.getProduct(productCode);
    
                // create the LineItem object
                LineItem lineItem = new LineItem(product, quantity);
    
                // display the output
                String message = "\nLINE ITEM\n" +
                    "Code:        " + product.getCode() + "\n" +
                    "Description: " + product.getDescription() + "\n" +
                    "Price:       " + product.getPriceFormatted() + "\n" +
                    "Quantity:    " + lineItem.getQuantity() + "\n" +
                    "Total:       " + lineItem.getTotalFormatted() + "\n";
                System.out.println(message);
                counter++;
                //Use the min and max methods of the Math class to update the values for the largest
                //and smallest line items:
                if(total > smallestLineItem){
                	total = largestLineItem;
                }
                float max = Math.max(smallestLineItem, largestLineItem);
                float min = Math.max(smallestLineItem, largestLineItem);
                
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.nextLine();
                System.out.println();
            }
            sc.close();
            System.out.println("Among the " + counter + " line items: "); 
            System.out.println("The smallest was " + min);//error: min cannot be resolved to a variable
            System.out.println("The largest was " + max);//error: max cannot be resolved to a variable
            System.out.println("Bye!");        
        }
    }
    But even if I moved them to the correct place (wherever that is), the user might go through the (y/n) while loop more than once, and if that happens, how is the program going to store the data from each loop iteration to use for comparison (in order to keep up with the changes of what the max and min should be)?

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why isn't my float total updating?

    The min should always be an argument of the Math.min method(). Similar for max.
    That way, you get a running result for min or max based on their previous
    values. Try the following with pencil and paper to see how it works.

    pseudocode example:

    Java Code:
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    while taking input {
                 value = get next value;
                 min = Math.min(min, value);
                 max = Math.max(max, value);
    }
    Note also that line 53 should be Math.min (once you fix the code).

    Regards,
    Jim
    Last edited by jim829; 07-02-2016 at 10:58 PM. Reason: grammar
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    Here's my updated code:
    Java Code:
    package murach.ui;
    
    import java.util.Scanner;
    import java.lang.Math;
    
    import murach.db.ProductDB;
    import murach.business.LineItem;
    import murach.business.Product;
    
    public class LineItemApp {
    
        public static void main(String args[]) {
            // display a welcome message
            System.out.println("Welcome to the Line Item Calculator");
            System.out.println();
    
            // create 1 or more line items
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            float total = 0;
            byte counter = 0;
            float largestLineItem = (float)0.0; 
            float smallestLineItem = (float)500.00; 
            float min = Float.MAX_VALUE;
            float max = Float.MIN_VALUE;
            while (choice.equalsIgnoreCase("y")) {
                // get input from user
                System.out.print("Enter product code: ");
                String productCode = sc.nextLine();
    
                System.out.print("Enter quantity:     ");
                int quantity = Integer.parseInt(sc.nextLine());
                
                // get the Product object
                Product product = ProductDB.getProduct(productCode);
    
                // create the LineItem object
                LineItem lineItem = new LineItem(product, quantity);
    
                // display the output
                String message = "\nLINE ITEM\n" +
                    "Code:        " + product.getCode() + "\n" +
                    "Description: " + product.getDescription() + "\n" +
                    "Price:       " + product.getPriceFormatted() + "\n" +
                    "Quantity:    " + lineItem.getQuantity() + "\n" +
                    "Total:       " + lineItem.getTotalFormatted() + "\n";
                System.out.println(message);
                counter++;
                //Use the min and max methods of the Math class to update the values for the largest
                //and smallest line items:
                if(total > smallestLineItem){//if total is more than 500,
                	total = largestLineItem;//then it's our new largest line item purchase
                }
                max = Math.max(smallestLineItem, largestLineItem);
                min = Math.min(smallestLineItem, largestLineItem);
                
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.nextLine();
                System.out.println();
            }
            sc.close();
            System.out.println("Among the " + counter + " line items: "); 
            System.out.println("The smallest was " + min);//error: min cannot be resolved to a variable
            System.out.println("The largest was " + max);//error: max cannot be resolved to a variable
            System.out.println("Bye!");        
        }
    }
    But the initialized values for smallestLineItem and largestLineItem are not changing from their initialized values after the user exits the (y/n) while loop, and I don't understand why. Here's some sample output:

    -----------------------------------------------------------------------------
    Welcome to the Line Item Calculator

    Enter product code: java
    Enter quantity: 20

    LINE ITEM
    Code: java
    Description: Murach's Java Programming
    Price: $57.50
    Quantity: 20
    Total: $1,150.00

    Continue? (y/n): y

    Enter product code: jsp
    Enter quantity: 5

    LINE ITEM
    Code: jsp
    Description: Murach's Java Servlets and JSP
    Price: $56.50
    Quantity: 5
    Total: $282.50

    Continue? (y/n): n

    Among the 2 line items:
    The smallest was 0.0
    The largest was 500.0
    Bye!
    -----------------------------------------------------------------------------

    What's the problem now?

    EDIT: is my if statement on lines 51 and 52 even doing anything?
    Last edited by Sam_JavaTheHut5580; 07-03-2016 at 06:47 AM.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Why isn't my float total updating?

    Change lines #54 and #55 to:

    Java Code:
    max = Math.max(max, largestLineItem);
    min = Math.min(min, smallestLineItem);
    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why isn't my float total updating?

    That won't help will it?
    largest and smallest need to need to be the ones that change.

    Indeed, the logic seems off.

    Sam, you need to work on one thing first, say the smallest part.
    No point clogging up the code with two sets of logic that don't work.

    So the loop is:
    Java Code:
    while line item to enter
        read in details.
        if cost of line item < smallest value then set smallest value to the new line item cost
        Add cost to total
        prompt user if they want to continue.
    That's it.
    That should give you your smallest value.
    No need for min/max variables. You just need to work with the line item cost and the smallest value you've saved.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Why isn't my float total updating?

    That code sure is a mess; the last couple of lines suggest that min and max should contain the smallest and largest values; but then again, the code was written by someone who doesn't understand what s/he is doing ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  15. #15
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by JosAH View Post
    That code sure is a mess; the last couple of lines suggest that min and max should contain the smallest and largest values; but then again, the code was written by someone who doesn't understand what s/he is doing ...

    kind regards,

    Jos
    You missed your coffee and Zware Van Nelle Jos? I'm pretty sure that's why s/he is here for help. OP will get there, once it clicks.

    @OP: Read the docs for Math.min(). It says: Returns the smaller of two float values. So, consider float currentMin = Math.min(10,100), what does variable currentMin contain? So if you want to keep track of the lowest float, you need to check your current number with the current min. This means you have to do something like: Math.min( currentMin, yourNumber). But since the method min() returns the smallest one (it doesn't change any variables), you need to assign it to currentMin to keep track of it. So the (pseudo)code would look like this:

    Java Code:
    float currentMin = Float.MAX_VALUE;
    
    while(myLoopRuns) {
       float someNumber = .....;
       currentMin = Math.min( currentMin, someNumber);
    }
    Every time the loop runs, the currentMin variable is updated with the smallest number.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by SurfMan View Post
    You missed your coffee and Zware Van Nelle Jos? I'm pretty sure that's why s/he is here for help. OP will get there, once it clicks.
    Nope, I still have enough espresso and a fresh load of tobacco arrived last weekend (bought in Belgium, it's still much cheaper there ;-) but the OP isn't putting enough effort in it: simply plugging in Math.min( ... ) and Math.max( ... ) in the code and hoping that things should work, isn't the way to go; afterwards complaining that directions don't make any 'freaking sense' only tells that the OP still doesn't understand what s/he is doing ...

    kind regards,

    Jos

    ps. after checking the barn: I also still have ample supplies of Grolsch beer, hurray!
    Build a wall around Donald Trump; I'll pay for it.

  17. #17
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by SurfMan View Post
    But since the method min() returns the smallest one (it doesn't change any variables), you need to assign it to currentMin to keep track of it. So the (pseudo)code would look like this:

    Java Code:
    float currentMin = Float.MAX_VALUE;
    
    while(myLoopRuns) {
       float someNumber = .....;
       currentMin = Math.min( currentMin, someNumber);
    }
    Every time the loop runs, the currentMin variable is updated with the smallest number.
    Tell you what. For now, lets just focus on getting the currentMin to work first (I'll worry about getting the max value later).

    The "someNumber" variable in your pseudo code in my code would be total (the fixed price of the item based on its productCode entered by the user * the user-entered quantity). Of course, the way my current code is:
    Java Code:
    package murach.ui;
    
    import java.util.Scanner;
    import java.lang.Math;
    
    import murach.db.ProductDB;
    import murach.business.LineItem;
    import murach.business.Product;
    
    public class LineItemApp {
    
        public static void main(String args[]) {
            // display a welcome message
            System.out.println("Welcome to the Line Item Calculator");
            System.out.println();
    
            // create 1 or more line items
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            float total = 0;
            byte counter = 0;
            //float largestLineItem = (float)0.0; 
            float smallestLineItem = (float)500.00; 
            float currentMin = Float.MAX_VALUE;
            //float max = Float.MIN_VALUE;
            while (choice.equalsIgnoreCase("y")) {
                // get input from user
                System.out.print("Enter product code: ");
                String productCode = sc.nextLine();
    
                System.out.print("Enter quantity:     ");
                int quantity = Integer.parseInt(sc.nextLine());
                
                // get the Product object
                Product product = ProductDB.getProduct(productCode);
    
                // create the LineItem object
                LineItem lineItem = new LineItem(product, quantity);
    
                // display the output
                String message = "\nLINE ITEM\n" +
                    "Code:        " + product.getCode() + "\n" +
                    "Description: " + product.getDescription() + "\n" +
                    "Price:       " + product.getPriceFormatted() + "\n" +
                    "Quantity:    " + lineItem.getQuantity() + "\n" +
                    "Total:       " + lineItem.getTotalFormatted() + "\n";
                System.out.println(message);
                counter++;
                //Use the min and max methods of the Math class to update the values for the largest
                //and smallest line items:
                if(total < smallestLineItem){//if total is less than 500
                	total = smallestLineItem;//then replace 500 (or current smallest) with total
                }
                //max = Math.max(total, largestLineItem);
                currentMin = Math.min(currentMin, total);
                            
                // see if the user wants to continue
                System.out.print("Continue? (y/n): ");
                choice = sc.nextLine();
                System.out.println();
            }
            sc.close();
            System.out.println("Among the " + counter + " line items: "); 
            System.out.println("The smallest was " + currentMin);//error: min cannot be resolved to a variable
            //System.out.println("The largest was " + max);//error: max cannot be resolved to a variable
            System.out.println("Bye!");        
        }
    }
    As long as the user chooses to enter y to continue, the amount of totals generated could be infinite. And if, for example, the user generated 12 totals that were all less than 500.00, the code as it is right now isn't smart enough to recognize that we have values less than the initialized 500.00. Here's some sample output proving my point:

    -----------------------------------------
    Welcome to the Line Item Calculator

    Enter product code: java
    Enter quantity: 5

    LINE ITEM
    Code: java
    Description: Murach's Java Programming
    Price: $57.50
    Quantity: 5
    Total: $287.50

    Continue? (y/n): y

    Enter product code: java
    Enter quantity: 4

    LINE ITEM
    Code: java
    Description: Murach's Java Programming
    Price: $57.50
    Quantity: 4
    Total: $230.00

    Continue? (y/n): n

    Among the 2 line items:
    The smallest was 500.0
    Bye!
    -----------------------------------------
    The final minimum should be 230.00, not 500.00.
    Also, the line:
    Java Code:
    currentMin = Math.min(currentMin, total);
    is supposed to select the smallest of the pair, so why am I still automatically getting 500.00 as the minimum of the user-generated totals?

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why isn't my float total updating?

    You're using far too many variables there.
    Seriously.
    You need one declared outside the loop, which is smallestLineItem, which should be Float.MAX_VALUE.
    Then just:
    Java Code:
    smallestLineItem = Math.min(smallestLineItem, lineItem.getTotal());
    That's it.
    When the loop has exited them smallestLineItem will be exactly what it says it is.

    No need to currentMin, or a total, or anything.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  19. #19
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why isn't my float total updating?

    To answer your question, look at the following snippets in isolation from the code.

    Java Code:
    float total = 0;
    float smallestLineItem = (float)500.00;
    float currentMin = Float.MAX_VALUE;
    Now do the following until the user quits.

    Java Code:
    if(total < smallestLineItem) {//if total is less than 500
         total = smallestLineItem;   //then replace 500 (or current smallest) with total
    //*** NOTE  your previous comment is wrong.  You are replacing replacing total with current smallest
    }
    
    //max = Math.max(total, largestLineItem);
    currentMin = Math.min(currentMin, total);
    Now work thru it.

    is total less than smallestLineItem? (or 0 < 500?
    yes, so total = smallestLineItem (or total = 500

    Now return the minimum of currentMin and total (or 500 and Float.MaxValue)
    currentMin = 500

    Second time thru, nothing changes.
    And that is what you print.

    You need to do two things.

    1. Think about what you are doing by working it out on paper.
    2. Follow Toll's advice.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  20. #20
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Why isn't my float total updating?

    Quote Originally Posted by Tolls View Post
    You're using far too many variables there.
    Seriously.
    You need one declared outside the loop, which is smallestLineItem, which should be Float.MAX_VALUE.
    OMG. When the book said to initialize the smallest value to a very large value, it meant use the .MAX_VALUE! Instead, I randomly picked 500.00. No wonder. The code now works like it should. Thanks :)

Page 1 of 2 12 LastLast

Similar Threads

  1. [Q] - pi as a float
    By oran0007 in forum New To Java
    Replies: 1
    Last Post: 09-30-2011, 10:33 AM
  2. regarding int and float
    By lakshmibvaraprasad in forum New To Java
    Replies: 2
    Last Post: 07-24-2011, 08:30 PM
  3. string to float
    By Sungron in forum New To Java
    Replies: 3
    Last Post: 02-02-2010, 09:23 AM
  4. Working with float
    By dardar in forum New To Java
    Replies: 8
    Last Post: 01-27-2010, 08:29 PM
  5. Float to String
    By mew in forum New To Java
    Replies: 4
    Last Post: 12-29-2007, 05:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •