if while do repeat dont know where to go!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 7 of 7

Thread: if while do repeat dont know where to go!

  1. #1
    Join Date
    Apr 2005
    Location
    IA
    Posts
    5

    Unhappy if while do repeat dont know where to go!

    Hi there this is a great forum so grateful to have found you all! It appears that a lot of the computer instructors in colleges are rude and do not know how to explain, explain until we get it. I thought it was just me! '

    Here is the program, it asks for input from user three seperate items then calculates the total including tax. My new part of this assignment is to have it repeat over and over until user enters incorrect value for quantity(can only be 1-100 inclusive) the price can only be (1.00-100). I am stuck I have tried while, if else, and it stops after the quantity, plus I cant figure out how to have it repeat the whole thing if all info is correct. I have seriously spent at least 36 hours going in one circle after another. ANY asssistance would be so greatly appreciated. The code below DOES not contain any loop or conditional statements this is the original program in which I need to add to.

    public static void main (String[] args)
    {
    final double TAX_RATE = 0.06; // 6% sales tax

    String Item;
    int quantity;
    double subtotal, totalcost, unitPrice;

    Scanner scan = new Scanner (System.in);

    NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
    NumberFormat fmt2 = NumberFormat.getPercentInstance();

    //request input from user
    System.out.print ("Enter the name of your item: ");
    Item = scan.next ();

    System.out.print ("Enter the quantity: ");
    quantity = scan.nextInt();


    System.out.print ("Enter the unit price: ");
    unitPrice = scan.nextDouble();

    subtotal = quantity * unitPrice;
    totalcost = (subtotal * TAX_RATE) + subtotal;

    System.out.println ("Your item was: " + Item+ ". The quantity purchased was " +quantity+ "the cost per item was: "
    +fmt1.format(unitPrice) + "for subtotal of " + fmt1.format(subtotal) + "with a total cost of " +fmt1.format(totalcost));

    }

    }

  2. #2
    Join Date
    Feb 2004
    Posts
    541
    To make that code repeat indefinately you need to use a while loop or a do-while loop. You'll have a condition that is tested against in the while loop, and when that condition evaluates to false the loop will end. I'll give you the basic structure, but you'll have to fit it to your code yourself.

    Code:
    boolean correctUserInput = true;
    
    while(correctUserInput)
    {
        getUserInput(); //I just used this to represent getting the input from the user.
    
        if(correctInput)
        {
            processUserInput();
        }
        else
        {
            correctUserInput = false;
        }
    }
    Ok, in the above code I create a boolean variable called correctUserInput. This is used as the test in the while loop. When the variable is true then the while loop will keep looping. When it is false then the while loop will end.

    In the loop I have a method called getUserInput(). I just used this as a quick way to represent the process of getting the use input, but you will use your scan.nextInt() methods etc.

    After getting the user input I have an if statement. This statement creates a fork in the code. If the expression used in the if statement evaluates to true only the first block of code executes, if it evaluates to false then only the second block of code evaluates (the one named else). You need to use this if statement to check that the quantity entered by the user is between 1-100. If it is then you process it accordingly, if it isn't then you end the while loop by setting the variable correctUserInput to false. This stops the while loop executing again.

    I'll leave it to you to adapt my general code to your own needs by substituting the various bits with your own code.

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Not to verride mikes suggestion...

    .. just an elaboration..
    Code:
    while (true) {  // never lets go until...
      //request input from user
      System.out.print ("Enter the name of your item: ");
      Item = scan.next ();
      if (Item.trim().length()==0) {
        System.out.println("Item name is invalid");
        continue;
      }
    
      System.out.print ("Enter the quantity: ");
      try {
        quantity = scan.nextInt();
      } catch (NumberFormatException ne) {
        System.out.println("Invalid numeric entry (must be a whole number)");
        continue;
      }
      if (quantity  < 1 || quantity > 100) {
        System.out.println("quantity must be in the range 1-100");
        continue;
      }
      System.out.print ("Enter the unit price: ");
      try {
        unitPrice = scan.nextDouble(); 
      } catch (NumberFormatException ne) {
        System.out.println("Invalid numeric entry");
        continue;
      }
      if (unitPrice < 1.0d || unitPrice > 100.0d) {
        System.out.println("unit price must be in the range 1.0-100.0");
        continue;
      }
    
      break; // finally ok, let him go...
    }
    Last edited by sjalle; 04-18-2005 at 12:30 PM.

  4. #4
    Join Date
    Apr 2005
    Location
    IA
    Posts
    5
    I'm confused on the second reply showing code with the try and catch, what would I put in the While boolean? Do I need to put it before the item coding even though I am not editing for info on the item? I tried the coding by moving the while to just in front of the quantity and this is what it looks like:
    while (quantity >0 || quantity >=100);
    {
    System.out.print ("Enter the quantity: ");
    try {
    quantity = scan.nextInt();
    } catch(NumberFormatException ne) {
    System.out.println ("Invalid entry");
    continue;
    }
    if (quantity <1 || quantity >100) {
    System.out.println ("quantity must be between 1-100");
    continue;
    }
    I get an error message that the first continue is outside of the loop. Also do I need to do anything to set up the Numberformat exception or is it being read by the boolean condition? thank you for your help

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    The boolean condition in the while stmt is "for eternity", that is, it does not leave
    the loop until the break statement at the end. This is written like
    while (true) {
    .
    .
    }

    The NumberformatException requires nothing more than the try-catch it is part of.
    If a numeric conversion fails inside the try-part it is caught in the catch-part.

    So, if all the try-cathces are passed the numerics are ok, and if the range conditions
    tests succeed then the code logic will reach the break statement at the end and
    finish the eternal loop. Without the break statement in the loop you would get a
    compile error (stetement after the loop are unreachable).

    I think you are better off leaving the loop as I posted it.

  6. #6
    Join Date
    Feb 2004
    Posts
    541
    I'm not sure your method does what was requested sjalle. If I understand the OP correctly, the while loop needs to execute indefinately if the correct data is entered, but exit if incorrect data is entered. Yours will break after one correct loop, but continue indefinately if incorrect data is entered.

  7. #7
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Uuups !! Quess I was a bit fast there

    Ok, then remove the break statement at loop end and replace all the continue
    statements with break statements....

    PS: to my defence, I have mislaid my glasses and until I get new ones I tend to
    just skim the text (must stop doing that)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center