Getting valid input with Scanner

I want to request that a user enter an integer from the keyboard using Scanner's nextInt metod, catch the InputMismatchException, and loop until a correct value is entered.
My attempt loops forever when the input is incorrect. It repeats the prompt but immediately goes to the catch clause. Can anyone shed some light on this for me - and point me in the direction of a solution?
Here is the code.
import java.util.*;
public class NumberFormatDemo
   public static void main (String[] arg)
       boolean goodInput = false;
       Scanner in = new Scanner(System.in);
       int age = 0;  //keep the compiler happy
       //loop until user gets it right
       while(!goodInput)
          try
             System.out.print("Please enter your age: ");
             age = in.nextInt();
             goodInput = true;
             System.out.println("You are " + age + " years old");
          catch(InputMismatchException e)
             System.out.println("The data you entered is invalid. Please try again.");
}Thanks,
kob

The data that the user entered is still being "pointed" at by the scanner. To fix this, try adding an "in.next()" statement in your exception handling block.
public class NumberFormatDemo {
    public static void main(String[] arg) {
        Scanner in = new Scanner(System.in);
        while (true) {
            try {
                System.out.print("Please enter your age: ");
                System.out.println("You are " + in.nextInt() + " years old");
                break;
            catch(InputMismatchException e) {
                System.out.println(in.next() + " is an invalid age. Please try again.");
}

Similar Messages

  • Validating input with onSubmit()

    Hello everybody,
    I would like to validate input on a jsp page, for example abc.jsp, with Java script and then submit the current form.
    I have seen solutions:
    <form action="..." onSubmit="return validate()">
    but what do I have to write in action definition if I do not want to go
    anywhere else but continue in the current form on the current jsp page?
    Are there any other ways to validate input before submitting the form?
    Thanks in advance for your help.
    Best regs
    Danny

    If for some reason you want a Validate button (in addition to a submit button) just add a regular button on your page that calls your validate() method on the onClick event.
    That being said validating the data just before submitting the page is typically a good idea.

  • Can not get analog input with SCC-SG04

    I have used the wizard and wrote a simple AI input channel loop with a digital readout. The voltage doesn't change.

    Well, I guess I'm not sure what all you have tried or how you have things set or configured. I would first try verifying the input through the test panels in MAX. Make sure you have your DAQ card set to NRSE mode, make sure you have your SC termination equipment set as the "Accessory" to the DAQ card under it's properties, double check your connections, then see if you can read the voltage through the MAX test panels. After you can read the voltage there, then you can try using a program. I hope this helps!
    Russell

  • How to get audio input with no line in jack?

    Apologies for this very basic question but I am increasingly lost and confused the more I search.
    I want to convert some audio cassette tapes into mp3. I have an older mac mini that I believe does not have any kind of audio input jack. I have heard from various people that 1) I just need a cable to convert RCA output to USB input (but as far as I can tell such a cable doesn't exist) 2) I need to buy a sound card 3) I need a special standalone piece of hardware.
    Which one is right? This is just a one time project and the audio is only voices so I don't want to spend any more than I need to.

    The Griffin iMic would work well for this.
    http://www.griffintechnology.com/products/imic

  • Need to isolate error with output with valid input (code included)

    Hey guys, this code will be a bit lengthy as I am posting from two separate Java files: Rectangle.java and RectangleTest.java - Basically I am stumped as to why even valid input keeps resulting in this message: System.out.println("\nThis is a SQUARE, not a Rectangle...Quiting...\n"); . Why am I getting this output? I seriously cant figure this out, and really what I am trying to do is take user input for four sets of coordinates, store them, do some simple math with them to determine if the object they form is a Rectangle and not a square. In the long run I am probably doing the whole thing wrong.
    Here is the Rectangle.java code:
    public class Rectangle {
         private int x1,x2,x3,x4,y1,y2,y3,y4;
         private int length;
         private int width;
         public Rectangle ()
              this.x1 = 0;
              this.y1 = 0;
              this.x2 = 0;
              this.y2 = 0;
              this.x3 = 0;
              this.y3 = 0;
              this.x4 = 0;
              this.y4 = 0;
         public Rectangle ( int x1, int x2, int x3, int x4, int y1, int y2, int y3, int y4)
              this.setX1(x1);
              this.setX2(x2);
              this.setX3(x3);
              this.setX4(x4);
              this.setY1(y1);
              this.setY2(y2);
              this.setY3(y3);
              this.setY4(y4);
              // First set x1, y1
              if (x1 > 0 && x1 < 20)
                   setX1(x1);
              else
                   this.x1 = 0;
              if (y1 > 0 && y1 < 20)
                   setY1(y1);
              else
                   this.y1 = 0;
              // Second set x2,y2
              if (x2 > 0 && x2 < 20)
                   setX2(x2);
              else
                   this.x2 = 0;
              if (y2 > 0 && y2 < 20)
                   setY2(y2);
              else
                   this.y2 = 0;
              // Third set x3,y3
              if (x3 > 0 && x3 < 20)
                   setX3(x3);
              else
                   this.x3 = 0;
              if (y3 > 0 && y3 < 20)
                   setY3(y3);
              else
                   this.y3 = 0;
              // Last set x4,y4
              if (x4 > 0 && x4 < 20)
                   setX4(x4);
              else
                   this.x4 = 0;
              if (y4 > 0 && y4 < 20)
                   setY4(y4);
              else
                   this.y4 = 0;
         }// exit constructor
         // Enter methods
         public int getArea()
              return length * width;
         public int getPerimeter()
              return (2*length) + (2*width);
         public boolean isSquare()
              if (length == width)
                    return true;
              else return false;
         public boolean isRectangle()
              if (length != width && length > width)
                    return true;
              else return false;
         // Enter Setters and Getters
         public void setLength(){
              this.length = ((x2-x1)^2 + (y2-y1)^2);
         public int getLength(){
              return length;
         public void setWidth(){
              this.width = ((x4-x1)^2 + (y4-y1)^2);
         public int getWidth(){
              return width;
         public void setX1(int x1) {
              this.x1 = x1;
         public int getX1() {
              return x1;
         public void setX2(int x2) {
              this.x2 = x2;
         public int getX2() {
              return x2;
         public void setX3(int x3) {
              this.x3 = x3;
         public int getX3() {
              return x3;
         public void setX4(int x4) {
              this.x4 = x4;
         public int getX4() {
              return x4;
         public void setY1(int y1) {
              this.y1 = y1;
         public int getY1() {
              return y1;
         public void setY2(int y2) {
              this.y2 = y2;
         public int getY2() {
              return y2;
         public void setY3(int y3) {
              this.y3 = y3;
         public int getY3() {
              return y3;
         public void setY4(int y4) {
              this.y4 = y4;
         public int getY4() {
              return y4;
    Code for RectangleTest.java:
    import java.util.Scanner;
    public class RectangleTest {
         public static void main(String[] args)
              int choice;
              int xFirst, xSecond, xThird, xFourth, yFirst, ySecond, yThird, yFourth;
              Scanner input = new Scanner(System.in);  // Scans or reads the inputs from the keyboard of user
              do {
                   System.out.print("\nTo START Enter '1'; ");
                   System.out.print("\nOr to QUIT Enter '0'; ");
                   choice = input.nextInt();
                   if (choice == 1)
                  // First Set
                  System.out.println("\nPlease enter the FIRST set of Coordinates\n");
                  System.out.print("Enter X1: ");
                  xFirst = input.nextInt();
                  System.out.print("Enter Y1: ");
                  yFirst = input.nextInt();
                  // Second Set
                  System.out.println("\nPlease enter the SECOND set of Coordinates\n");
                  System.out.print("Enter X2: ");
                  xSecond = input.nextInt();
                  System.out.print("Enter Y2: ");
                  ySecond = input.nextInt();
                  // Third Set
                  System.out.println("\nPlease enter the THIRD set of Coordinates\n");
                  System.out.print("Enter X3: ");
                  xThird = input.nextInt();
                  System.out.print("Enter Y3: ");
                  yThird = input.nextInt();
                  // Third Set
                  System.out.println("\nPlease enter the FOURTH set of Coordinates\n");
                  System.out.print("Enter X4: ");
                  xFourth = input.nextInt();
                  System.out.print("Enter Y4: ");
                  yFourth = input.nextInt();
                  // Instantiating the Rectangle class to test it
                  Rectangle rectangle1 = new Rectangle(xFirst, xSecond, xThird, xFourth, yFirst, ySecond, yThird, yFourth);
                  int lengthRectangle1 = rectangle1.getLength();
                  int widthRectangle1 = rectangle1.getWidth();
                  int area = rectangle1.getArea();
                  int periRect = rectangle1.getPerimeter();
                  // Check Shape type
                  if (rectangle1.isRectangle())
                       System.out.println("\nThis is a valid Rectangle\n");
                  else if (rectangle1.isSquare());
                        System.out.println("\nThis is a SQUARE, not a Rectangle...Quiting...\n");
         }while (choice != 0);
         System.out.println("Bye for now!");
    }

    NPP83 wrote:
    Essentially, I am trying to achieve the following:
    1. Store the Cartesian coordinates for the four corners of a Rectangle
    2. Verify that the supplied coordinates (by the user) do infact make a Rectangle and not a Square.
    Since I don't physically have a Length and Width, but just points, I have to use a little math to create a Length and Width and I came up with ((x2-x1)^2 + (y2-y1)^2) to find the length of one side. I thought I would store this as the way to set the Length/Width (setLength & setWidth), but I havent been able to find a way to bridge the user's input in the main() method of the test program to use the values in this formula. Even then, I am not sure if this simple step would at all help validate the object created by the four sets of points is a Rectangle. I thought that a Rectangle might be created by simply by deductive math where if the Length > Width or Length < Width and Width != Length then I would have a what I was looking for.One side is (X2 - X1) the next side is (Y3 - Y2) the 3rd and 4th sides are: (X4 - X3) and (Y4 - Y1).
    Edited by: morgalr on Mar 29, 2010 3:40 PM -- the following comment added:
    You should check out getBounds, it may be what you are looking for.

  • Getting No input file specified. in php with index.php

    I just installed on a server (soalris10/u6 sparc) Web Server 7.0u4 (upgraded from u3), and I am now getting "No input file specified." for any php doc root, I now have to type the full path to get the main page.
    I am using the php part of the Sun coolstack 1.3.1 and it used to work fine with web server 7.0 u3, but now after the upgrade its not loading index.php
    for example I am going to http://server.domain.com/wiki used to work by loading index.php, but now I have to type the full index... http://server.domain.com/wiki/index.php?title=Main_Page
    Any help is appreciated.

    If you're not currently using a php.ini, you can pass the parameter to PHP via your FastCGI configuration. Something like:
    Service fn=responder-fastcgi
            app-path="/export/WS7/third-party/php/php_fcgi"
            bind-path="$(lc($urlhost))"
            req-retry=5
            type="*magnus-internal/fastcgi*"
            app-env="PHPRC=/export/WS7/fooBaz/config"Now place a file called php.ini in /export/WS7/fooBaz/config and make sure that the UID Web Server is running as has permission to read it.
    Common syntax is KEY = Value. An example would be:
    cgi.fix_pathinfo = Off
    session.bug_compat_42 = Off
    session.bug_compat_warn = Off
    magic_quotes_gpc = Off
    memory_limit = 128M
    post_max_size = 128M
    upload_max_filesize = 128M
    fastcgi.logging = true

  • How I get started using voice input with mac mail?

    Just got a new Imac.  have had Apple computers for a long time.  Want to start using voice input with mail.  How do I get started?

    Apple's voice input options are the following:
    Dictation
    This allows you to speak a phrase and have the system enter it as text in any text field, be it a name and address form or a text editor like Pages or Word. The settings for this service are in the Dictation system preferences, and by default you activate it by pressing the Fn key twice in a row and then speak the desired phrase after you hear the bing sounds.
    Speakable Items
    This option allows you to somewhat control the Mac's interface elements by speaking key phrases to the system. This option is enabled in the Accessibility system preferences, and is at the bottom of the listed services. In here you can turn on the service and calibrate it to properly hear your voice, set a "listening key" (similar to the Fn key for Dictation), and then enable various command libraries.

  • Since most recent OS update, my iMac intel won't open my HP Officejet 4500 scanner. I have un-installed and re-installed the 10.8.3 update and the dame with HP drivers. I get the essage (HP scanner won't open because of a problem". Suggestions???

    Since most recent OS update, my iMac intel won't open my HP Officejet 4500 scanner. I have un-installed and re-installed the 10.8.3 update and the dame with HP drivers. I get the essage (HP scanner won't open because of a problem". The printer works, but not the scanner. Suggestions???

    It's possible that you need new drivers from HP, in order to be compatible with OS X 10.8.3. Looking at HP website, they haven't released new drivers since last November. You might need to wait for new drivers or contact HP to push for an update.
    http://h10025.www1.hp.com/ewfrf/wc/softwareCategory?os=219&lc=en&cc=us&dlc=en&sw _lang=&product=3919448#N218

  • FM to get Controlling area with Input Fiscal Year Variant..

    Hi,
    I need a Function module to get Controlling Area with Input fiscal Year Variant(PERIV).
    Regards,
    Deepthi.

    Hi,
    Check the FMs whether it satisfies your requirement.
    FERC_DEFAULT_GET
    FERC_PARAMETERS_GET
    Thanks,
    Nithya

  • How to get result of MDM validation expression with type warning?

    I need  to get result of MDM validation expression with type WARNING (in automatic execution),
    but - method validationResult.getFailedValidations(..) returns validation if it has type ERROR,
    so all Warnings treated only as success despite it returned false or true.
    My question - how can I get that 'false or true' expression resut for validation.
    thanks

    Hello Vladimir
    By my opinion, hook warning exception isn't make sense because after warning message data will be change(upload).
    Moreover  if you start validation from WF Warning exception doesn't work at all.
    If you want to do some data changes you should use and hook Error exception.
    Regards
    Kanstantsin Chernichenka

  • Problem with Scanner input

    I want to take an int as first input and string with spaces as 2nd input via scanner input method... it takes int input and immediatly prints the output
    without taking string input.... where is the bug.... here is the code...
    import java.util.*;
    import java.io.*;
    public class Ud2
    public static void main(String[] args)
    Scanner in=new Scanner(System.in);
    int x=in.nextInt();
    String s=in.nextLine();
    System.out.print("the no is "+x+" and name is "+s);
    if the prob is due to new line charcter in the stream then how to remove or
    ignore it..?
    plzzz help.......................

    in.nextLine();Insert the above line after your nextInt call. Why? Because nextInt() does not consume the end of line(EOL) character. So when you call nextLine() you assign the EOL to s

  • [INS-08109] Unexpected error occurred while validating inputs at state 'get

    Facing that on a windows 2003 server on installing 11gR2 on an installed 11.1.0.6
    [INS-08109] Unexpected error occurred while validating inputs at state 'getOCMDetails'.
    that's in the first step on the installer

    Very stupid installer !
    I've omitted my email, then pressed no in the next message, it passed that step!

  • Non-SysAdmins get error 18456 Severity 14 State 11 Login Failed for user _ Reason Token-based server access validation failed with an infrastructure error.

    I have a SQL 2008 R2 system (10.50.4000) where I'm having problems connecting any user that is not a SysAdmin.  Example: I setup a new SQL Login to use Windows Authentication and grant that user db_datareader on the target database.  The user attempts
    to connect using Excel client or Access or SQL Management Studio and receives Error 18456.  The SQL Server Logs shows Error 18456 Severity 14 State 11 Login Failed for user _ Reason Token-based server access validation failed with an infrastructure error.
    The strange part is that if I temporarily grant the user the sysadmin server role then the user can connect successfully and retrieve data.  But, if I take away that sysadmin server role then the user can no longer connect but again receives the Error
    18456 Severity 14 State 11 Login Failed for user _ Reason Token-based server access validation failed with an infrastructure error.
    We've turned off UAC on the client machine to see if that was the problem, but no change.
    I have dropped and re-added the user's SQL Login (and the related database user login info).  No success.
    The Ring Buffers output shows:
    The Calling API Name: LookupAccountSidInternal
    API Name: LookupAccountSid
    Error Code: 0x534
    Thanks for any help.
    -Walt

    Yes, you understand correctly.  The user is logging onto a workstation (not the server) with a Windows Authenticated id.  The user is using either Excel or Access or SSMS and connecting to the server using a Windows Authenticated SQL Login account.
     If the account has sysadmin role (which is only for testing) then the connection is successful.  If I take away sysadmin role from the account then the connection is unsuccessful and the SQL Server Log shows Error
    18456 Severity 14 State 11 Login Failed for user _ Reason Token-based server access validation failed with an infrastructure error.
    (SQL Authentication is not an option here.  I must use Windows Authentication).
    Any other troubleshooting assistance you can offer would be appreciated.  Thanks.
    -Walt 

  • Problems with getting user input

    Hi All,
    I want to get user input from a command line and i am NOT using a GUI.
    The user can still see their password when they are typing it in.
    Is there anyway to show '******' when they type in their password??
    This is what I have so far..
    public static void getPassword() {
    System.out.print("Enter password-->");
    DataInputStream input = new DataInputStream(System.in);
    try{  
    password = input.readLine();
    catch (IOException e){
    System.out.println("ERROR " + e);
    Any help would be greatly appreciated.
    Thanks
    Kal.

    Kal,
    I'm pretty sure you're going to need some kind of GUI (either a Java window or an HTML page) to get the desired effect. There might be a way to set the echo character in the command line, but I'm not sure.
    - Sheepy

  • Ins-08109 unexpected error occurred while validating inputs at state 'quick install'

    Dear All,
    I successfully configure clusterware for 2 node rac db. But when i try to install Oracle DB Software i am getting below error on 4 step .
    ins-08109 unexpected error occurred while validating inputs at state 'quick install'.
    Kindly advice over the same.
    Thanks in advance.

    Thanks John for your update,
    Actually whenever i ask a question on OTN and Sybrand replied over the same every time instead of giving solution or advice he always try to insult other. I know that he is very senior to me and i am here posting query not to waste important time of anyone but to get the solution. Yes i forgot to update the i goggled and applied the recommendation before posting my query here. But this is not the correct way to advice anyone. Infact he also cross out this level where i am. If you think i hurt sentiments of anyone i feel sorry for that. But this is not the right way to advice in fact you all are seniors and we are coming here to learn from you guy's. OTN is not private property of anyone.
    One thing more to say like you advice me calmly it's better to understand me how to do things accordingly now i will do that. Thanks again for your help and i will take care of all these things in future.
    Actually the problem mentioned above i faced first time and after google i didn't get any blog or site with the same mentioned error instead it will give me link mentioned below:-
    [Ins-08109] Unexpected Error Occurred 'Installoptionsui'.
    But mine was
    [ins-08109] unexpected error occurred while validating inputs at state 'quick install''
    I tried one of the blog that states that similar problem occurs when clusterware is not up. First i check whether clusterware is up or not i found that it is up. But still i restarted it and try the installation again but getting the similar problem again.
    In one blog it is mentioned that due to listener misconfiguration the problem occurs. I crosschecked listeners are configured from grid home.
    So applied both the sol which i get by typing the same error which i mentioned above but not successful to get the solution.
    In some website it is suggested that try to contact Oracle Support for the same.
    Ok the problem is sorted out,I do a fresh installation of OS, Clusterware and DB, now i am not facing the same problem. I think the problem is related to group permission. Now this time i mention all the details what i do and what is the result i think now its better to understand.

Maybe you are looking for

  • T.code for checking stock at WM level

    Hi Gurus,                I want to check the warehouse stock at Storage type level in previous week,Can any one give me T.Code where we can satisfy this requirement Regards Narayana

  • Migrate SBS Server 2008 with Exchange 2007 to Exchange 2013

    I have looked at the documentation to co exist 2007 and 2013.  However I am concerned as it talks about changing the dns name to something like legacy, as the dns name that is used for outlook to connect is the name of the server.  So here is my ques

  • How do I get my correct email back to my iphone

    I think I screwed up, I was attempting to sync my Iphone 5 to Itunes, and in the process, all my current information is gone, including my correct email account, and the data is all from my old Iphone 3.    I've tried everything to reverse/restore it

  • Program to run several FICO transaction in background

    Hello everyone. I received a request to run, in background, a list of transactions. I found most of the reports that can be used to run the transaction in back ground. Here is what I did so far. 1. I created a report that is collecting on the screen

  • ABAP Proxy with Party

    Party is using to group business systems of one partner? I have in one party business system which comunicate with Abap Proxy. But when I send message to SAP PI, I receive message with out Party. BS_ERP(abap-proxy) -> SAP PI Configuration looks like: