Why do i have to use nextLine() when there is an InputMismatchException

I dont understand why do i have to use this line of code to avoid an infinite loop here...help appreciated.
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
     public static void main(String [] args){
     Scanner in = new Scanner(System.in);
     int n = 0;
     while(true){
          try{
               System.out.println("Input a number:");
               n = in.nextInt();
               break;
          }catch(InputMismatchException exc){
               System.out.println("Error, non-valid input.");
               //in.nextLine(); <--If i use this line of code it doesn't get into an infinite loop
                         System.out.println("Integer read is: " + n);
}

Rix87 wrote:
When i run the program if i input something that triggers the exception, it infinitely loops through the question and the catch method block outputs, weirdest thing of all is that i can't even input again after the exception is thrown, but with nextLine() it avoids that, but i still dont understand why do i have to use nextLine().Exactly what I said.
You enter "A". The exception is thrown. The "A" is not consumed. It calls nextInt on "A" again... and again... and again...
If you do nextLine, the "A" and the newline are consumed.
Even on good input, I don't think nextInt consumes the EOL.

Similar Messages

  • Why do I have 6 installed printers when the correct number is 0?

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
              <key>InstalledPrinters</key>
              <array>
                        <string>MANUFACTURER:1060;MODEL:9491</string>
                        <string>MANUFACTURER:1439;MODEL:4152</string>
                        <string>MANUFACTURER:2652;MODEL:17664</string>
                        <string>MANUFACTURER:APPLE;MODEL:SD Card Reader</string>
                        <string>MANUFACTURER:Apple Inc.;MODEL:BRCM20702 Hub</string>
                        <string>MANUFACTURER:LaCie;MODEL:XtremKey</string>
              </array>
              <key>Manufacturers</key>
              <array>
                        <string>1060</string>
                        <string>1439</string>
                        <string>2652</string>
                        <string>APPLE</string>
                        <string>Apple Inc.</string>
                        <string>LaCie</string>
              </array>
    </dict>
    </plist>
    My SD Card slot is corrupted.
    I was under the impression BRCM was Broadcom Wireless hardware?
    LaCie XtremKey is a USB flash drive.
    What do they have to do with printers. Something queer is going on with this printer business. I don't own a printer. I haven't needed to print a page in years. But TM crashes prior to completing a backup. The logs don't say much but they talk about the xxx/cups folders being fiddled with (as the reason for the failure of Time Machine to...function).

    Rix87 wrote:
    When i run the program if i input something that triggers the exception, it infinitely loops through the question and the catch method block outputs, weirdest thing of all is that i can't even input again after the exception is thrown, but with nextLine() it avoids that, but i still dont understand why do i have to use nextLine().Exactly what I said.
    You enter "A". The exception is thrown. The "A" is not consumed. It calls nextInt on "A" again... and again... and again...
    If you do nextLine, the "A" and the newline are consumed.
    Even on good input, I don't think nextInt consumes the EOL.

  • HT201250 Why do i have to use the password for time capsule every time i start my computer

    Why do I have to use thr password for time capsuel every time I start my imac?

    With hindsight, the previous response I got from Apple was just a way of shelving the problem.
    Having just had to reset my password after another 3 months, I contacted Apple again, and it happened that the senior advisor whom the phone agent consulted had had exactly the same problem as me, and had found that iTunes could fix it.  However when I spoke to iTunes they told me I needed to speak to Apple ID account security.  The Apple ID account security representative spoke to a senior adviser, then told me that it would be fixed after I reset my password.  However I am not convinced that anything was actually done, so I may be back here in another 3 months ...
    To modify Roger's advice, the solution I was given is: go to https://expresslane.apple.com ; select 'All Products and Services' in the first column, 'iTunes' in the second column, 'iTunes Store' in the third column, then "Account Management" and "Apple ID account security", then "Talk to Apple support now". A complication is that the "Talk to Apple support now" option only appears when UK English is selected.  So you either need to select UK at the top, or find another way of making phone contact (the email link just went back to the person in iTunes)!

  • WHy should we have to use to update ipod touch

    WHy should we have to use to update ipod touch

    Your question does not make sense. Please clarify.
    GamingChamp wrote:
    WHy should we have to use to update ipod touch

  • I have downloaded pages 5 and installed and have been using it. when i turned my computer on today and tried to open a document, it was not there! How do i find pages 5?

    i have downloaded pages 5 and installed and have been using it. when i turned my computer on today and tried to open a document, it was not there! How do i find pages 5?

    Are you sure you are in the same User account as you installed Pages 5?
    Peter

  • Why do I have a black sreen when I try to watch a youtube video. I have sound but no video and if I click on the black screen firefox crashes.

    why do I have a black sreen when I try to watch a youtube video. I have sound but no video and if I click on the black screen firefox crashes.

    Also update firefox to version 23, you are currently on Firefox 3.6.
    * [[Update Firefox to the latest version]]

  • Why do I have a black screen when I merge to HDR from Bridge?

    Why do I have a black screen when I merge to HDR from Bridge?

    Back up all data.
    Triple-click the line of text below to select it, the copy the selected text to the Clipboard (command-C):
    /Library/Internet Plug-ins
    In the Finder, select
    Go ▹ Go to Folder
    from the menu bar, or press the key combination shift-command-G. Paste into the text box that opens (command-V), then press return.
    From the folder that opens, remove any items that have the letters “PDF” in the name. You may be prompted for your login password. Then quit and relaunch Safari, and test.
    The "Silverlight" web plugin distributed by Microsoft can also interfere with PDF display in Safari, so you may need to remove it as well, if it's present.
    If you still have the issue, repeat with this line:
    ~/Library/Internet Plug-ins
    If you don’t like the results of this procedure, restore the items from the backup you made before you started. Relaunch Safari again.

  • When and why do i have to use a Network-Path?

    Hello,
    i'm wondering when i why i have to use a Network-Path in KM.
    I'm able to connect to a File-System Repository, even if i have no Network-Path defined.
    - both run on W2K Server
    - EP runs on host EP (not an Domain-member)
    - Filesystem is provided by host FS (Domain-member)
    - EP is started with the default local-user SAPServiceEP6
    - on the FS host, i have defined also a local-user SAPServiceEP6 (because EP always wants to logon with these credentials, i have checked this in the windows securitylog of host FS)
    - no network-path defined
    So regarding the fact, that everything is working, can anybody tell me when i have to use a Network-Path?
    Thanks in advance
    Frank

    Hi,
    for example if you want to access a share that only access is granted for a given user. The idea is having a superuser with privileges on the other computer to do things like checking ACLS.
    Another example, how can you access windows shares when running the portal in Unix? Using a network path.
    REgards,
    Miguel

  • Why do I have to use SELECT INTO clause in a Stored Proc ?

    Hi,
    I'm new to oracle. I've bought Oracle Database 10g SQL and Oracle Database 10 A beginner's Guide, two books from Oracle press but I can't find any answer for that.
    Why when I'm writing a Stored Procedure with a SELECT statement do I have to use an INTO clause ?? And why when the select returns more than one row do I have to use a cursor ? By the way is this the only way to return more than one row from a stored procedure ?
    Any help will be appreciated.
    Regards.
    S. Nunes

    Sounds like you may have some experience with other databases (SQL Server, maybe?) which allow you to create stored procedures which implicitly return result sets simply by embedding select statements.
    In Oracle, the correct way to do this is using ref cursors.
    See the following link for a good explanation:
    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • Why do I have to use silverlight to view Netflix movies?

    I'm wondering why I have to use Silverlight to play Netflix movies. When I opened Netflix and selected a movie to play in my Firefox browser a gray page opened up and the only option was to play the movie using Silverlight. I have a sneaking suspicion that it's a requirement by Netflix as Netflix is partnered up with Silverlight, a Microsoft product and has some sway over what's able to be played with this addon. Why is there no alternative. I really like the new Firefox but still we're wanting for just a little more control of who does what on our machine.
    Respectfully,
    Tom V.

    Netflix determines which program their movies are to use. Firefox has no control over it.

  • Why do I have to enter passwords when they are synced in keychain

    I have Keychain turned on on my iPad 3.  Up until this summer when there was an update to IOS 7, they appeared automatically when I went to a web site where one was stored in Keychain.  Suddenly, I had to start to type in the first letter and then the keyboard would appear with a small line above it for autofill.  If I move from one page of the NYTimes to another, I have to re-sign-in - a total nuisance. 
    I updated to IOS 8 hoping that this issue would be fixed.  Nope!  Updated to IOS 8.1 - still the same.  Yet on my old iPhone 5 and on my new iPhone 6, the web sites pop right up with me already signed in.  Huh?  What's going on here?
    Is this unique to the iPad or is some setting wrong?

    Hi, Thatchcote. 
    Thank you for visiting Apple Support Communities.
    This sounds like you may have Private Browsing enabled.  The article below will show you how to disable this feature.
    Safari isn't automatically filling in account names and passwords on some websites.
    iOS 7.1.1 or later:
    Go to Settings > Safari > Passwords & AutoFill and make sure that Names and Passwords is on.
    Go to your Home screen and open Safari. If Safari is black or dark instead of white or gray, Private Browsing is on. Safari doesn't save account names and passwords when Private Browsing is on. To turn off Private Browsing:
    On iPad, tap the the plus icon in the upper-right corner of the Safari page, then tap Private in the lower-left corner.
    On iPhone and iPod touch, tap in the lower-right corner of the Safari page, then tap Private in the lower-left corner.
    Get help using iCloud Keychain
    http://support.apple.com/kb/TS4644
    Cheers,
    Jason H.

  • Why do we have to use SwingUtilities.invokeLater() to update UI status?

    I just don't understand very well why we have to use SwingUtilities.invokeLater() to update UI status. Why not just new a thread in actionPerformed() method and do time consuming tasks in this thread and update UI status in it? Some tutorials say it is not safe to update UI status not in Event Dispatch Thread, I don't understand, why is it not safe? Can anyone provide a scenario for this? I just write an example, a button and a progressbar, click button, progressbar keeps updating value. I just create a new thread to do this, don't find any issue. Thanks.

    [Swing single threaded rule|http://www.lmgtfy.com/?q=swing+single+threaded+rule]
    db

  • Why do I have to buy Acrobat when it's always been available on the Creative Cloud?

    I'm a subscriber of the Creative Cloud and have been for quite a while
    Why do I now have to buy Acrobat when it's always been available as one of the CC apps?
    And why did the "trial" version of Acrobat DC wipe out my personal Acrobat Pro XI?

    Hi,
    Please refer to the help document below:
    https://helpx.adobe.com/creative-cloud/kb/acrobat-dc-uninstalls-acrobat-11.html
    Regards,
    Sheena

  • Do I have to use lock when I am reading data from a table

    Hi,
    When i am reading data from a table , do I have to set a lock on that table .
    Is it necessary for us to set the lock on a table when I am reading data from the table.
    When I am updating the table , do I have to set a lock on the table ?
    If yes, then what sort of lock-read lock,write lock or shared lock?
    Regards,
    Sushanth H.S.

    check it out,
    Lock objects are use in SAP to avoid the inconsistancy at the time of data is being insert/change into database.
    SAP Provide three type of Lock objects.
    - Read Lock(Shared Locked)
    protects read access to an object. The read lock allows other transactions read access but not write access to
    the locked area of the table
    - Write Lock(exclusive lock)
    protects write access to an object. The write lock allows other transactions neither read nor write access to
    the locked area of the table.
    - Enhanced write lock (exclusive lock without cumulating)
    works like a write lock except that the enhanced write lock also protects from further accesses from the
    same transaction.
    You can create a lock on a object of SAP thorugh transaction SE11 and enter any meaningful name start with EZ Example EZTEST_LOCK.
    Use: you can see in almost all transaction when you are open an object in Change mode SAP could not allow to any other user to open the same object in change mode.
    Example: in HR when we are enter a personal number in master data maintainance screen SAP can't allow to any other user to use same personal number for changes.
    Technicaly:
    When you create a lock object System automatically creat two function module.
    1. ENQUEUE_<Lockobject name>. to insert the object in a queue.
    2. DEQUEUE_<Lockobject name>. To remove the object is being queued through above FM.
    You have to use these function module in your program.
    check this link for example.
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    tables:vbak.
    call function 'ENQUEUE_EZLOCK3'
    exporting
    mode_vbak = 'E'
    mandt = sy-mandt
    vbeln = vbak-vbeln
    X_VBELN = ' '
    _SCOPE = '2'
    _WAIT = ' '
    _COLLECT = ' '
    EXCEPTIONS
    FOREIGN_LOCK = 1
    SYSTEM_FAILURE = 2
    OTHERS = 3
    if sy-subrc 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
    Normally ABAPers will create the Lock objects, because we know when to lock and how to lock and where to lock the Object then after completing our updations we unlock the Objects in the Tables
    http://help.sap.com/saphelp_nw04s/helpdata/en/cf/21eea5446011d189700000e8322d00/content.htm
    purpose: If multiple user try to access a database object, inconsistency may occer. To avoid that inconsistency and to let multiple user give the accessibility of the database objects the locking mechanism is used.
    Steps: first we create a loc object in se11 . Suppose for a table mara. It will create two functional module.:
    1. enque_lockobject
    1. deque_lockobject
    before updating any table first we lock the table by calling enque_lockobject fm and then after updating we release the lock by deque_lockobject.
    Select the radio button "Lock object"..
    Give the name starts with EZ or EY..
    Example: EYTEST
    Press Create button..
    Give the short description..
    Example: Lock object for table ZTABLE..
    In the tables tab..Give the table name..
    Example: ZTABLE
    Save and generate..
    Your lock object is now created..You can see the LOCK MODULES..
    In the menu ..GOTO -> LOCK MODULES..There you can see the ENQUEUE and DEQUEUE function
    Reward if helpful

  • Why do I have to use the tab key even more to tab between page elements.

    Firefox versions prior to ver 4 I used the tab key to tab between page elements (form elements, buttons, etc). I upgraded to ver 4 and now when I tab from form element to form element I first see a gray line outlining the element area and then another press of the tab the element becomes active for me to use. I now have to use double the tab keys to move between form elements.

    Hello new_mac_user, see if the next works
    # In the [[Location bar autocomplete|Location bar]], type '''about:config''' and press '''Enter'''. The about:config "''This might void your warranty!''" warning page may appear.
    # Click '''I'll be careful, I promise!''', to continue to the about:config page.
    # in search field type (or copy/paste from here) '''accessibility.tabfocus'''
    # double-click on it and change the value to '''4''' (probably you have 1 the default on mac)
    # click ok, exit firefox and restart it.
    with the above you give focus to links (and linked images) only when you press the tab key.
    see for more info : http://kb.mozillazine.org/Accessibility.tabfocus
    https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Preference_reference/accessibility.tabfocus
    thank you

Maybe you are looking for

  • How to sync with multiple computers?

    I have my iTunes library on my MacBook and all of my Apple devices synced accordingly. My family also has an iMac, and I would like other family members to be able to sync from the iMac. I know I can use Home Sharing to allow the iMac to view/play th

  • Read last shutdown information

    Hello. Where can I read information about last shutdown (a type of shutdown - normal, transactional, immediate, abort ...)? Thanks.

  • Script does not pick up values as intended

    Hi I have written a CALC routine where in i want to do the following: -If there is any input done for that rate in the month, the routine should do nothing - If there is no input in that rate account in the month, it should pick up the previous perio

  • OAS w/Remote 8i database

    I've installed OAS 4.0.8.1 on NT sp5 connecting to an 8i db on a Sun box. I am able to bring up xml type docs via the browser, however when I attempt to access the db I get http 500 internal error.

  • Lync 2010 Spell Check

    Hi Is there a way to get spell checking working with Lync 2010 without having to set up third party software? I have Office 2010 installed and I did read somewhere that if you download and install Office 2013 proofing tools it should work, but it has