Help needed with 'while' loop please

Problem: When a non-integer is entered, the console displays "Enter a wager > java.util.InputMismatchException" intermitentlly.
Here is the source codes
===================
import java.util.Scanner;
public class Test {
     private static int bankBalance = 1000;
     public static void main(String []args) {
          System.out.println("You entered: " + wager());
      Ask user for a wager, which must not be greater than 'bankBalance' and
      must be a valid Integer. Continue asking until a valid wager is entered.
     private static int wager() {
          Scanner scanner = new Scanner(System.in);
          int input = bankBalance + 1;
          boolean isValid = false;
          while( (input > 1000) || (isValid == false) ) {
               try {
                    System.out.print("Enter a wager > ");
                    input = scanner.nextInt();
                    isValid = true;
               } catch(java.util.InputMismatchException im_exc) {
                    System.out.println(im_exc.toString());
          return input;
}

It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
get input from user
set counter to first number entered
while counter less than/ equal to second number
      check if number is even
           if even, add to even_sum
           else output counter, along with its square
      increment counter by one
end while
output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
Good Luck

Similar Messages

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • Help needed with CSS menu please

    Hello
    Could someone give me a hand with a CSS menu I am struggling
    with please?
    I want each of the blue menus to have a black border around
    it (so 4 borders in total). And how do I make each menu have a
    closer gap? I need them squashed up a little bit more vertically.
    The code is as follows -
    <style type="text/css">
    #ddblueblockmenu{
    width: 179px;
    border-top: 1px solid #FFFFFF;
    border-right: 1px solid #FFFFFF;
    border-bottom: 0 solid #FFFFFF;
    border-left: 1px solid #FFFFFF;
    #ddblueblockmenu ul{
    margin: 0;
    padding: 0;
    list-style-type: none;
    font: normal 75% 'Trebuchet MS', 'Lucida Grande', Arial,
    sans-serif;
    border: #000000;
    #ddblueblockmenu li a{
    display: block;
    padding: 5px 0;
    padding-left: 9px;
    width: 169px; /*185px minus all left/right paddings and
    margins*/
    text-decoration: none;
    color: white;
    background-color: #2175bc;
    border-bottom: 11px solid #FFFFFF; /*change border gap size
    here*/
    /*border-left: 1px solid #1958b7;
    * html #ddblueblockmenu li a{ /*IE only */
    width: 187px; /*IE 5*/
    w\idth: 169px; /*185px minus all left/right paddings and
    margins*/
    #ddblueblockmenu li a:hover {
    background-color: #2586d7;
    border-left-color: #1c64d1;
    #ddblueblockmenu div.menutitle{
    color: white;
    border-bottom: 1px solid black;
    padding: 1px 0;
    padding-left: 5px;
    background-color: #FFFFFF;
    font: bold 60% 'Trebuchet MS', 'Lucida Grande', Arial,
    sans-serif;
    </style>
    <body>
    <div id="ddblueblockmenu">
    <ul>
    <li><a href="whoarewe.htm"><strong>What We
    Offer</strong></a></li>
    <li><a
    href="guidelines.htm"><strong>Professional
    Guidelines</strong></a></li>
    <li><a
    href="workshops.htm"><strong>Workshops</strong></a></li>
    <li><a href="contactus.htm"
    style="border-bottom-color: white; font-weight:
    bold;">Contact</a></li>
    </ul>
    </div>
    </body>
    </html>
    Any help is very greatfull appreciated!!
    Tom

    "Gary White" <[email protected]> wrote in message
    news:[email protected]..
    > On Tue, 23 May 2006 11:42:13 +1000, ".: Nadia :. ACE :."
    > <[email protected]> wrote:
    >
    >>If you want a border the same color around the whole
    menu, you can use the
    >>short-cut method:
    >>
    >>border { 1px solid #FFF;}
    >
    >
    > Uh ...
    >
    > #ddblueblockmenu{
    > width: 179px;
    > border: 1px solid #fff;
    > }
    >
    um... that's what I meant... the OP had all four sides styled
    separately,
    with 0 for one side... but mentioned he wanted a border on
    all sides....
    hence my arrow pointing out the side that had 0 for border
    and what could
    be used as a shortcut method of styling the border....
    Maybe my post wasn't exactly clear ;-)
    Nadia
    Adobe� Community Expert : Dreamweaver
    http://www.csstemplates.com.au
    - CSS Templates | Free Templates
    http://www.perrelink.com.au
    - Web Dev
    http://www.DreamweaverResources.com
    - Dropdown Menu Templates|Tutorials
    http://www.adobe.com/devnet/dreamweaver/css.html

  • Help needed with optimising loops

    hello again,
    am wondering if there're any suggestions to help optimise my code. i'm having a mindblock now. i need to retrieve the top 10 occurring elements in my array. attached is my code.
    it's taking much to long... i'm nesting a loop of 40,000+(original file contents) in a loop of 1,000+(non-repeating items of the original file contents) in a loop of 10. i can't think of how else to do it. any suggestions?
               //get top 10 most frequently visited hosts
               //start by tabulating hits for each website, using non-repeated items
               //add the top to the 1st arraylist slow, until we get 10 items
               String championSite = "";
               String currentSite = "";
               int championCount = 0;
               int currentCount = 0;
               int bufferCount = 0;
               String bufferSite = "";
               StringTokenizer st;
               ArrayList hitCounter = new ArrayList();
               boolean removed = false;
               for(int extLoop=0;extLoop<10;extLoop++)
                    for(int i=0;i<nonRepeatedItems.size();i++)
                         bufferCount = 0;
                         //currentSite = String.valueOf(nonRepeatedItems.get(i));
                         for(int count=0;count<parsedContents.size();count++)
                              System.out.println(count);
                              st = new StringTokenizer(String.valueOf(parsedContents.get(count)));
                              for(int random=0;random<6;random++)
                                   st.nextToken();
                              bufferSite = st.nextToken(); //get the website column
                              //get address without path information, index 7 because "HTTP://"
                              bufferSite = bufferSite.substring(0,(bufferSite.indexOf("/",7)));
                              if(String.valueOf(nonRepeatedItems.get(i)).equalsIgnoreCase(bufferSite))
                                   bufferCount++;
                                   //delete the current pointer in parsedContents
                                   //maintain the pointer count?
                         //store the first
                         if(i==0)
                              currentCount = bufferCount;
                              currentSite = String.valueOf(nonRepeatedItems.get(i));
                              championCount = currentCount;
                              championSite = currentSite;
                         else
                              //store only if greater than existing value
                              if(bufferCount>currentCount)
                                   currentCount = bufferCount;
                                   currentSite = String.valueOf(nonRepeatedItems.get(i));
                                   championCount = currentCount;
                                   championSite = currentSite;                                    
                    //top10webSites.add(championSite+" "+championCount);
                    if(championCount!=0)
                         System.out.println(extLoop+1+". "+championSite+" with "+championCount+" visits.");
                    championSite = "";
                    championCount = 0;
                    //remove the current topsite from the original list
                    for(int i=0;i<nonRepeatedItems.size();i++)
                         if(String.valueOf(nonRepeatedItems.get(i)).equalsIgnoreCase(currentSite))
                              nonRepeatedItems.remove(i);
                              break;
               }

    Knowing the forums today, there's really probably like 10 responses already though I see none.
    The best way would likely be to use a HashMap to keep track of the occurances of each item. Example:
    List<String> stringList = new ArrayList<String>(); //with tons of items
    Map<String, Integer> tally = new HashMap<String,Integer();
    for ( String item : stringList ) {
      if ( tally.containsKey(item) ) {
        tally.put( item, tally.get(item)+1 );
      else
         tally.put( item, 1);
    //then loop through each entry in tally.entrySet() to find out which has most entries
    edit Surprise, surprise.
    Edited by: endasil on Nov 30, 2007 3:05 PM

  • Help me with for loop please...............

    hi guys i m just new bie as you know
    i gotta print these things........
    from 7 stars to 1 star........
    i did it like this but it only produce
    in this way,,,,,,
    how do we actually padding the space and print it as the example........
    help me guys whoever experts in for loops my code is........
    class triangle
         public static void main (String[] args)
              a(7);
         public static void a (int num)
              for (int j = num ; j > 0 ; j--)
                   for (int i = 0 ; i < j ; i++)
                        System.out.print("*");
                   System.out.println ();
    }

    You really need a better screen name,
    The problem is is that you want to print out a descending number of stars
    preceded by a number of spaces . the number of spaces for a line is the number of characters - number of stars so
              for (int j = num ; j > 0 ; j--)
    HERE print the required spaces!
                   for (int i = 0 ; i < j ; i++)
                        System.out.print("*");
                   System.out.println ();

  • Help needed with nokia 6300 please

    I have nokia 6300 , I have unstalled many programs on it (like messenger and google earth java files) some of them needs to connect to internet through gprs but they give a message "Subscribe to packet transfer first". But my device connects to web and opens pages through explorer.
    Please if any can give help and thanks to all.........

    Are you sure your connecting by gprs to the net, or by other means say WIFI or wap? There are many packet services & not all are provided by ISP unless one subscribe to it.
    Knowledge not shared is knowledge wasted!
    If you find it helpfull, it's not hard to click the STAR..

  • Help needed with Synergy 4500 please

    I have inherited a set of BT Synergy 4500 phones and have been trying to get them set up but am having problems - can somebody please give me some help?
    First, there are three handsets but one is showing as number 4, (I suspect there might have originally been 4 but one has disappeared).  I've been trying to renumber this but no luck.
    When I lift the phone to make a call I get a noise that sounds like an engaged tone - not like an ordinary dial tone, and I can't seem to dial out - nothing happens.
    One of the handsets indicates there are three unanswered calls - how can I clear this? 
    TIA 

    There are help pages here http://bt.custhelp.com/app/answers/detail/a_id/11489/~/bt-synergy-4500
    The guide should tell you how to clear the calls.
    There are some useful help pages here, for BT Broadband customers only, on my personal website.
    BT Broadband customers - help with broadband, WiFi, networking, e-mail and phones.

  • Help needed with this tutorial please

    Hello in this InsertUpdateDelete tutorial at:
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/index.jsp
    or
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/inserts_updates_deletes.html
    and in this paragraph:
    Changing the Column Components
    and this statement
    In the Visual Designer, select the top Drop Down List component in the Table.
    "It's pretty confusing because there isn't a Drop Down List component in the Table as far as i can tell. There is a Drop Down List on the canvas up above this data table, but that has already been bound in a previous process, here is that previous proces:"
    Configuring the Drop Down List
    Select the Drop Down List in the Visual Designer and, in the Properties window, change its General > id property to personDD.
    Right-click the personDD Drop Down List in the Visual Designer and choose Bind to Data from the pop-up menu. The Bind to Data dialog box appears.........
    Can anyone tell me where i can get help with this tutorial or where i can download the finished program so i can sync up with what is actually being referenced in the questional statement that i mentioned above please?
    Thanks very much!
    BobK

    In Step 5 of "Changing the Column Components" you change the Trip Type column to a drop-down list.
    5. Select TRIP.TRIPTYPEID from the Selected list and make the following changes:
    * Change the Header text field from TRIPTYPEID to Trip Type.
    * Using the drop-down list, change the Component Type from Static Text to Drop Down List.
    6. Click OK to enforce your changes and dismiss the window. If the table columns are too wide after performing the above steps, you can resize them by selecting the first component in each column and dragging its selection handles.
    7. In the Visual Designer, select the top Drop Down List component in the Table. Right-click and choose Bind to Data from the pop-up menu. The Bind to Data dialog box opens.

  • Help needed with my form - PLEASE!

    My form on avarislaw.com is working properly.
    The form attach file area should not be mandatory but for some reason it still apears even when I change this in BC.
    Please help!
    Thanks
    Andy

    You need to remove the javascript validation for that form element in the HTML of the form as well.

  • Help need with dire problem please.

    Hi all, my 24 inch iMac has spat the dummy! I installed a trial version of Photo Shop and somehow while attempting to install the program I got a weird series of screen images with the prohibition sign......never seen this one before.
    Tried to do a restart, but the grey Apple screen came up with rapidly repeating logo's, 'prohibition' and question marks and others too.
    I though maybe an 'archive and install' might be the way to go, but first tried all the keyboard commands to get it going, not successful!
    Initially the archive and install got going OK but I decided to abort the installer and go back, restart the installer and try to get into disc repair. I thought this would enable me to delete the offending installer for Photo Shop.
    Now I find I cannot get the Leopard disc to fire up. A grey screen comes up with the circulating wheel, but no boot up. I have Disc Warrior, but this disc also is not recognised.
    I have tried all this several times to no avail. I have everything backed up to my EHD. Cannot access this either at the moment. Thank goodness for my MacBook.
    Can anyone shed some light on this problem. I would be most grateful if you could.
    Ron Begg, Australia

    Since your startup volume install was aborted, your disk never got "blessed" as a startup volume, that's one reason why your running into so many problems.
    Also you might be "locked out" of the volume due to install abort.
    Do this First -
    Restart with the Command and S keys held down (single user mode)
    and enter the following commands
    (one at a time - pressing return after entering them):
    mount -uw /
    chown root:admin /
    chmod 1775 /
    again at the command prompt type:
    /sbin/fsck -fy
    Repeat fsck until no errors found.
    Once fsck has run successfully-
    again and lastly at the command prompt type:
    reboot
    If everything was successful, you should be able to get your
    Leo install disk to boot or anything else you would like to try.
    Kj

  • Help needed with iPhoto settings Please ?

    Hi,
    When I click the "places" tab iPhoto states that I am not connected to the internet..when I AM
    I see that there are other users experiencing the same issue as me, mostly with no replies at all.
    Surely somebody out there knows how to rectify this problem ?!?
    My macbook pro is 3 weeks old......Mavericks 10.9.4
    I have not downloaded many apps yet, and have not changed any iPhoto settings.
    I have Location Services set to enabled.
    My internet connection is Not dropping.
    Really hoping there is a kind and understanding person out there willing to spend a few minutes to help a newbie.

    Hi again LN..... I have now set it to the other option offered > Automatically <
    Directly underneath that it says: include location information for published items
    I haven't a clue what that means or if I should have that ticked ? 
    Thank you so much for the answer to my places / internet connection issue 

  • Help needed with Mac Mini please

    I have just noticed the start up "dong" has stopped working and I believe this could indicate some problems somewhere, but how (without going to a "genius bar", would I go about finding out the problems?
    I know it has a faulty cd/dvd drive as it no longer burns cd's or even play dvd's (going to be fun when Snow Leopard is released :/ )
    Any advice of any programs I could run etc to try and solve these issues if possible please, and I can not format the drive do to the dvd not working.
    Many thanks, Jim!

    I wouldn't worry about the startup chime. It's been years since my Mini had one. Still works fine.
    For an Intel Mini, you can try an SMC reset. Can't hurt; might help:
    http://support.apple.com/kb/HT1543
    I suspect the CD/DVD drive is just worn-out or too dirty.

  • Since installing Firefox 4 I cannot install addons - help needed with new browser please

    Have tried to install add-ons, and whilst they appear to have installed nothing is added to the tools add-ons button.

    This can be caused if one of the files that stores details of installed extensions is corrupt.
    # Open your profile folder, for details of how to find it see https://support.mozilla.com/kb/Profiles
    # Close Firefox
    # Delete the following files if they exist, extensions.cache, extensions.rdf, extensions.ini and extensions.sqlite
    # Re-start Firefox, it will then rebuild the list on installed extensions

  • Help needed with BBDM 5.0.1 IP Modem

    Hi I was happily connecting thru the Net via the IP Modem in BBDM ver 5.0.1 all this while. Only this happened yesterday. Accidentally during the connection, my 9500 was disconnected from the USB cable. From that moment on, I cannot access the Net using the IP Modem feature. Tried to reboot the laptop as well as the 9500 but now all I get is the connecting message and then a pop up saying there is a hardware failure in the connecting device (or modem) ie the BB 9500.
    I even uninstalled BBDM 5.0.1 and reinstalled ver 5.0 and also updated back to 5.0.1 - same story. I can still access the Net via the BB browser etc
    Advise please thanks in advance

    I have the disc and re-installed a couple of time. No positive result. PSE 09 which I bought thereafter is giving a lot of problems also!!!
    Date: Wed, 8 Jun 2011 10:31:24 -0600
    From: [email protected]
    To: [email protected]
    Subject: Help needed with Elements 5.0
    Doesn't really help either of us very much but I'm also having the same problem with Elements 5. I downloaded the program so I don't have disks to reinstall. And it seems from the other reply that Adobe has given up with the "old program," which incidentally was working fine until two days ago. Maybe I'll have to think about PSE9!
    >

Maybe you are looking for