Scanner, nextInt() -- what if somebody enters a string?

How can i detect if the user enters a string? When somebody enters a string it causes some errors.
my code.
int iVar = input.nextInt();
if (iVar == 1)
          System.out.println("option 1");
else if (iVar == 2)
          System.out.println("option 2");
else if (iVar == 3)
          System.out.println("option 3");
else if (iVar == 4)
          System.out.println("option 4");
else // any integer
          System.out.println("wrong");
}if i entered a string, it causes an error
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at compro1_nested_if_else_statement.main(nested_if_else_statement.java:32)
How will i detect that? for numbers (int) it is working fine.

something like this has worked for me:
        System.out.print("Please enter a number: ");
        while (!input.hasNextInt())
            input.nextLine();
            System.out.println("Please enter only Integer input");
        int iVar = input.nextInt();

Similar Messages

  • The string version of a scanner.nextInt

    is it possible to use a scanner.nextInt for string's?
    I want to filter out a lettercode
    input :
    23 54 64 34 23 VV
    If this is the input, than i want my program to know that there is a VV in it.
    Hopefully you understand what I mean.

    So, here's some more to the program.
    First of all, I introduced accessor specifiers, public, private. There's another one, protected - and a 'hidden' one, package private. You may want to read about accessors. Find info in the Java tutorial, especially
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    Now, I also generalized the amount of tokens expected from the user. You are now free of the restriction that the user must enter exactly four tokens. You'll also see an if condition that aborts the demo() method if no value has been entered. All this is a better programming practice, because it makes your program more robust against unexpected input. Robustness is an important criterion in programming.
    I leave you with the improved version. Keep learning, and don't hesitate to ask further question! Thanks for dropping by.
    --------------------- New version -------------------------
    package p3;
    import java.util.Scanner;
    public class Testfile
        Scanner scanner;
        String  data;
        String  lettercode;
        int     newvalue;
        int     sum;
        public static void main (String [] args)
            new Testfile ().demo ();
        private void demo ()
            int nTokens         = 0;
            int iTokenChoice    = 0;
            // Get data from user
            System.out.println ("enter your data");
            Scanner scanner = new Scanner (System.in);
            String entireInput = scanner.nextLine ();
            // Extract tokens. Last token must be one of three possibilities,
            // "AA", "BB" or "CC"
            String [] tokens = entireInput.split (" ");
            nTokens          = tokens.length;
            if (nTokens >= 1)
                iTokenChoice     = nTokens - 1;
                String letterCode = tokens [3];
                if ("AA".equals (letterCode))
                    programA (tokens);
                else if ("BB".equals (letterCode))
                    programB (tokens);
                else
                    programC (tokens);
        private void programA (String [] tokens)
            sum = GetSum (tokens);
            System.out.println ("The sum calculated by programA is " + sum);
        private void programB (String [] tokens)
        private void programC (String [] tokens)
        private int GetSum (String [] tokens)
            int     iToken      = 0;
            int     nTokens     = 0;
            String  temp        = null;
            int     ti          = 0;
            int     ret         = 0;
            nTokens = tokens.length - 1;
            ret     = 0;
            if (nTokens >= 1)
                for (iToken = 0; iToken < nTokens; iToken ++)
                    temp    = tokens [iToken];
                    ti      = Integer.parseInt (temp);
                    ret     = ret + ti;
            return ret;
    }Here's the output from a few example sessions:
    Run 1. Just hit ENTER
    enter your data
    Run 2.: Entered no value, then AA
    enter your data
    AA
    The sum calculated by programA is 0
    Run 3.: Entered 1 value, then AA
    enter your data
    1 AA
    The sum calculated by programA is 1
    Run 4.: Entered 2 values, then AA
    enter your data
    1 34 AA
    The sum calculated by programA is 35
    While with the old version I got a java.lang.ArrayIndexOutOfBoundsException, if I entered not enough values or programC would have always executed if I entered too many values:
    enter your data
    1 2 AA
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
         at p3.Testfile.demo(Testfile.java:39)
         at p3.Testfile.main(Testfile.java:19)
    Now a question for you to think about:
    In the GetSum method I wrote the statement:
    nTokens = tokens.length - 1;What would happen if I had written:
    nTokens = tokens.length;Try and test!

  • Wanted: Popup which allows the user to enter one string

    Hello,
    as the topic states, I am searching for a (modal) popup which lets the user enter one string in a text field and returns this string.
    I am currently using the function module 'POPUP_TO_GET_ONE_VALUE' for this purpose which works quite good - BUT it has one major drawback: the string that is returned is entirely in capital letters. This is not acceptable as I want to build a case-sensitive search based on the input...
    Any suggestions are greatly appreciated !
    Best regards,
    Patrick

    Anand,
    I'm just finished with your first reply - checked out 'POPUP_TO_SEARCH_VALUE' - and you already gave a second option - marvellous !
    Will try the other one out right now.
    You are right, the parameters that reference to the DDIC made me wonder and decide against this FM when I searched through all the available popups some time ago.
    To your first reply:
    the popup is quite good. It does indeed deliver a 'case preserved' string. What I don't like is the checkbox and the fact, that the confimation button is labeled 'search' rather than just the 'ICON_OK'. I should mention at this point that I reuse the popup in other scenarios where the string is not used for a search but to name certain objects. Again an all uppercase string (or all lowercase string as well) is unwanted.
    Now on to the second popup...
    Regards,
    Patrick

  • What is the difference between string != null and null !=string ?

    Hi,
    what is the difference between string != null and null != string ?
    which is the best option ?
    Thanks
    user8729783

    Like you've presented it, nothing.  There is no difference and neither is the "better option".

  • What is the difference between String Constant and Empty String Constant

    What is the difference between string constant which does not contain any value and the Empty string constant?
    While testing a VI which contain a normal string constant in VI analyzer, it gives error to change string constant with the empty string constant?
    Please Reply
    prabhakant
    Regards
    Prabhakant Patil

    Readability.
    Functionally, they are the same. From a coding standpoint, the Empty String Constant is unambiguous.
    It is empty and will always be; good for initialization. Also, because you can not type a value into and Empty String Constant, someone would need to conciously replace it to set a 'default' value that is something other than NULL.
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • Both my iPad and iPhone have ios8 On either device in Calendars edit shared with add person when I enter an email address and press add nothing happens - just goes back to edit screen and what I have entered has gone. No error message or any clue

    Both my iPad and iPhone have ios8
    On either device in Calendars> edit >shared with> add person when I enter an email address and press add nothing happens - just goes back to edit screen and what I have entered has gone. No error message or any clue about why I cant share my calendar. Please help.

    UDPATE:
    Spoke with Express lane, and issue was escalated.  Kudos to the support guys that handled this one (Brian and Yi).  Went through everything in detail and took all the crash dumps off the iphones and ipads to send to engineering.
    After backing up the contacts, the recommendation was to delete all contacts in  iCloud.  Doing that caused my iCloud to crash (in the browser), so more crash dumps were sent to apple.
    Eventually got all contacts deleted, then did a resync.  Looks like IOS devices are coming back to life and syncing again.
    Also, Outlook iCloud connector has just been updated to ver 1.0.1 so i installed that on their recommendation.
    BOTTOM LINE workaround:
    1. Backup contacts
    2. Delete contacts in iCloud
    3. Delete accounts on IOS devices
    4. Recreate accounts on IOS devices.
    Hoping a real root cause can be found and real fix implemented.  This has caused me to doubt the stability of iCloud, so i will procees with caution.

  • Pre-parsing user-entered query strings

    I'm looking for a robust PL/SQL (or other) script for pre-parsing user-entered query strings, so I can make intermedia work like familiar search engines. (Think Yahoo/Alta Vista.) It has to deal gracefully and intuitively with embedded special characters, boolean constructs, quoted literals, etc.
    Has Oracle released anything like this?

    There's example code in "The Button" download from http://technet.oracle.com/products/intermedia in the file "avquery.java".
    Putting the query directly into ABOUT() also works if you don't need to clean up end-user input.
    null

  • Belle Refresh: What to be entered in "facebook" de...

    In a contact entry of belle, there are details like "facebook", "gizmo", "msn", "yahoo".. etc.
    now what should i enter in that details, if i want to use "facebook" detail ??
    Attachments:
    18112012010.jpg ‏436 KB

    Hi there TD777,
    What that Facebook field is referring to is the address for your contacts? i.e. a couple of years back, Facebook gave users the option of setting their own username rather than just being a number. Previously, someone would be www.facebook.com/15151165116111611515677. Now someone could set their own username i.e. www.facebook.com/bobthegeekygecko. The Facebook field is asking you for that: bobthegeekygecko.
    P.s. if you visit any of the examples I just posted, they are not real, so they are de-identified.
    Hope this helps.

  • Add WHERE criterias in addition to what the user enters on search page

    Hi,
    This may be a simple problem, but I have not been able to solve it.....Is there a way for me to code another search criteria in addition to what the user enters?
    I'm trying to create a simple search page. Basically, user logs on, i get his acoount number and save it in a variable. Then whatever the user's search criterias are , I want to add "AND ACCOUNT = ???."
    I've tried:
    In the processRequest, retrieve his account number using a VO, stored account number in variavle x and then call a initQuery(x) for the VO to get only the rows that he should be able to see. Problem A: I get 'SQLStmtException' when I test the page by trying to do a Simple Search. So to fix that, in the VOImpl, I added these two calls -- setWhereClauseParams(null); setWhereClause(null); -- after the executeQuery(). After I did this, ran into Problem B: the user could search any record that wasn't associated with his account.
    I also tried to dynamically create the vo using createViewObjectFromQueryStmt("Select * from table where account = " + x) but was not successful. The page didn't render and I received a ClassCastException similar to this thread -- Re: How to Create OAViewObject programatically
    I'm new to OAF and would appreciate any pointers on how to implement this.
    Thanks,
    LL

    Hi,
    I assume that you haven't tried the following steps..if you have and still get an error, give us the SQL statement error that is coming up. If I misunderstood your requirement, could you elaborate.
    I assume that when the user logs in you get the account number automatically.
    You could define the VO to have the following where condition 'WHERE ACCOUNT=:1'.
    Then you set the account id from the user using setWhereClauseParams(0,accountid) and call executeQuery. This would limit the result to that user.
    This will work in addition to any other search fields that might have been used in the query.
    For e.g with just the account id the sql that will be fired is
    Select attribute1, attribute2....from Tablexxx where account = :1
    Any other user search criteria given in the page will result in a ssql query like the following
    select * from (Select attribute1, attribute2 ...from Tablexx where accoount = :1) where newattribute like `%xx`
    Hope this helps. Let us know if you still have issues.
    Thank you,
    Arun

  • I have an I-mac with Max OS X vers. 10.6.8. Have tried to install both an old Photoshop 7.0 and an Photoshop Elements but it does not work. 7.0 I bought many years ago end the Elements came with a Canon scanner. What to do? Regards Peter Lindgren

    en

    I´ll check the messages. Elements 4.0.
    Peter
    9 dec 2014 kl. 18.44 skrev Jeff A Wright:
    I have an I-mac with Max OS X vers. 10.6.8. Have tried to install both an old Photoshop 7.0 and an Photoshop Elements but it does not work. 7.0 I bought many years ago end the Elements came with a Canon scanner. What to do? Regards Peter Lindgren
    created by Jeff A Wright in Downloading, Installing, Setting Up - View the full discussion
    Peter Lindgren do you receive any specific error messages when you attempt to install Photoshop 7 or Photoshop Elements?  What version of Photoshop Elements are you installing?
    If the reply above answers your question, please take a moment to mark this answer as correct by visiting: https://forums.adobe.com/message/6999366#6999366 and clicking ‘Correct’ below the answer
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page:
    Please note that the Adobe Forums do not accept email attachments. If you want to embed an image in your message please visit the thread in the forum and click the camera icon: https://forums.adobe.com/message/6999366#6999366
    To unsubscribe from this thread, please visit the message page at , click "Following" at the top right, & "Stop Following"
    Start a new discussion in Downloading, Installing, Setting Up by email or at Adobe Community
    For more information about maintaining your forum email notifications please go to https://forums.adobe.com/thread/1516624.

  • I probably misclicked when I activated the security lock on the iPhone and now I can not figure out what password I entered. Moreover, I have patches and funky looking phone so I can not restore iphine pres itunes. Please advice.

    I probably misclicked when I activated the security lock on the iPhone and now I can not figure out what password I entered. Moreover, I have patches and funky looking phone so I can not restore iphine pres itunes. Please advice.

    Your only recourse is to force it into DFU mode:
    Turn your phone off and connect your cable to the computer, but not the device just yet. Start up iTunes. Now, hold down the home button on your phone and plug it in to the cable - don't let go of the button until iTunes tells you it's detected a phone in recovery mode. Now you can restore to factory settings.

  • How can I put data to cell according to what data you entered first?

    I'm using DDE to simulate vi to excel, it display the data to excel correctly, according to what data i entered, but i already assign specific cell to a specific data. i want that for example, the data that has been read is SOG row 1 column 3. and FOG row 2 column 3. how can i distinguished what data read first? bec. if you first entered data FOG it will entered in row 2 and if you entered SOG it will appeared in row 1, if you have a lot of entered data you will not distinguished what data enetered first.
    can you please give me an idea how can i solve this?
    Thank You

    I'm not totally sure if I understand your question, but it seems to me that you have two pieces of data - SOG and FOG. This data will be written to your Excel file in the same location each time. Are you writing FOG and SOG from the same VI? If so, why not use a shift register to keep order? Another option is to insert a time stamp next to the SOG or FOG data and then view the time stamp to know the order. Or, you could write the data to a simple text file. Keep appending the data. When you want to know the order, just open the text file and you will have the insertion sequence there. Good luck.

  • Installer requires serial number, what do I enter?

    I'm trying to install the trial version of Livecycle ES4, but the installer that come with the .zip file is asking for the serial number. What do I enter to gain access to the trial version?

    I am having the same issue. What's the point in having a trial version if they won't let you install it?

  • App Store won't update my apps. Keeps asking me update card info. However when I do it keeps decking card. I have checked card to what I have entered. Starting to annoy me

    App Store won't update my apps. Keeps asking me update card info. However when I do it keeps decking card. I have checked card to what I have entered. Starting to annoy me

    Hey Duddy1888,
    Thanks for the question. Try changing your payment information to “None”. If you are unable to select “None” as a payment option, see the following resource:
    Why can’t I select None when I edit my payment information?
    http://support.apple.com/kb/TS5366
    Using an existing iTunes Store or App Store account
    If you have an unpaid balance or payment due, you can't select None as your payment type. To see which order you need to pay for, view your purchase history. When you sign in to the store, you may see a message that there was a billing issue with your last order. Click the Billing Info button to see the order.
    After you pay for the order, you can change your payment information to None.
    Additional Information:
    iTunes Store: My credit card's security code or zip code does not match my bank's records
    http://support.apple.com/kb/TS1646
    iTunes Store & Mac App Store: About payment card authorization holds
    http://support.apple.com/kb/HT3702
    Thanks,
    Matt M.

  • When updating my spreadsheets (iWork '08) the umbrella icon appears in the dock, and the software backs up what I've entered. I don't recall setting this up.

    When updating my spreadsheets (iWork '08) the umbrella icon appears in the dock, and the software backs up what I've entered. I don't recall setting this up.
    Anyone know what's going on?

    Thanks, but I do know what the software is for as I occasionally use it to back up stuff onto my iDisk, but I don't understand why I'm getting backups of stuff like spreadsheets when I haven't set the system up for it.
    The only back up I do have set up is for my iPhoto album to back up to my Lacie external hard drive...that's all.

Maybe you are looking for

  • Z77a-gd65 debug 60 - does not output video, keyboard and mouse don't light up

    Hello guys! I've had this motherboard since August 2012. It worked great until my street suffered from a power outage yesterday, and since it came back on I can't figure out what exactly is wrong with my mobo. The power up process occurs fine until d

  • Only one song playing at a time

    I recently was upgraded to ITunes 7.6.29, and found that I had to reimport all my music -- ITunes couldn't find it. That hurdle passed, I then found that I had to redo my playlists. I fixed that. Now, though, when I listen to a playlist only one song

  • HELP! Just got iPhoto 6 w/ my Tiger upgrade, and pictures won't show up

    Last week, my 1 1/2 year old Powerbook G4 was having issues that eventually led to me having to replace the hard drive. The new hard drive came with the Tiger OS (was previously on Panther) and the new iLife suite, including iPhoto 6. All of my photo

  • How to Publish Motion 5 templates

    How to publish motion 5 templates to to another editor's Final Cut X project? Basically I want to have one motion 5 designer built templates for use with other Final Cut X projects on other systems.

  • Any tutorial for creating a business object type in the BOR ?

    Hello, I want to create an object in the BOR, can you please pin point good tutorial to follow explaining how to create a business object type. Points are awarded Regards