Scanner input being forgotten

I am new to Java and playing around with Scanner input instead of BufferedReader. In the following code the Scanner input appears to be forgotten at the end. When asking if the user wants to repeat another person, if I omit the 2nd Scanner input, the nextLine is not executed or at least ignored. Is there a time limit or input limit for how long Scanner input will work?
import java.util.Scanner;
public class Java0504
     public static void main (String args[])                                    
          String repeat = "Y";
          while (repeat.equals("Y"))
               System.out.println();
               Scanner input = new Scanner(System.in);
               System.out.print("Enter 1st Name ===>> ");
               String firstName = input.nextLine();
               System.out.print ("Enter last name ===>> ");
               String lastName = input.nextLine();
               System.out.print ("Enter your area code ===>> ");
               String areaCode = input.nextLine ();
               System.out.print ("Enter your prefix ===>> ");
               String prefix = input.nextLine ();
               System.out.print ("Enter the last four digits of your phone number ===>> ");
               String lastFour = input.nextLine ();
               System.out.print ("Enter your age ===>> ");
               int age = input.nextInt ();     
               System.out.println ();
               System.out.print ("Do you have another person Y/N ===>> ");
               Scanner input2 = new Scanner(System.in);
               repeat = input2.nextLine ();     
          System.out.println ();                    
}

I think you probably need this:
String dummy = input.nextLine();after the line:
int age = input.nextInt();And then, add the following (and eliminate the input2, as suggested):
repeat = input.nextLine(); after the "another person Y/N".
Otherwise, I think the input.nextLine() after the "Y/N" will just consume the "return" that was pressed when the user entered the age.
That is, the last few lines would be:
int age = input.nextInt ();
System.out.println ();
String dummy = input.nextLine();
System.out.print ("Do you have another person Y/N ===>> ");
repeat = input.nextLine();

Similar Messages

  • Follow Up to Scanner Input from File

    Alright, I have another problem. My code is this:
    for (int j = 0; j < username.length; j++) {
         String line = input.nextLine();          // Create a temporary String that will store each line
         // Check if the temporary line isn't empty
         if (line.length() > 1) {
                 numAccounts++;
                 username[j] = line.substring(10);
                 password[j] = input.nextLine().substring(10);
                 System.out.println(username[j]);
         } else {     // If the temporary line is empty, go back on the loop to prevent empty array entries
                  j--; }
         }It runs through once, and then stops. Here are the declarations:
    static int numAccounts = 1;
    static String[] username = new String[numAccounts];
    static String[] password = new String[numAccounts];
    static  Scanner input = new Scanner(new BufferedReader(new FileReader("account.txt")));Which was done outside of the main method.
    Why does the loop iterate only once?

    Woah, don't need to get all heated up about something I'm doing wrong. I'm just trying to figure this out. Sorry if I'm getting on your nerves.
    So anyways, I did the ArrayList method with your suggestion of making it an ArrayList of Objects. This is what I have so far:
    // Declare the ArrayList that will store all the Account Objects retrieved from the database
    static ArrayList<Account> accounts = new ArrayList<Account>();
    while (input.hasNextLine()) {
        String line = input.nextLine();          // Create a temporary String that will store each line
        // Check if the temporary line isn't empty
        if (line.length() > 0) {
             //System.out.println(line);
             String currentName = line.substring(10);
             String currentPass = input.nextLine().substring(10);
             Account current = new Account(currentName, currentPass);
             accounts.add(current);
    }Yes, I stuck with using the line.length() > 0, because trying to use line != null doesn't work properly for me. Not entirely sure why. Just throws IndexOutOfBoundsException when it's called.
    And my Account Object class is as so:
    class Account {
         static String username, password;
         Account(String username, String password) {
              this.username = username;
              this.password = password; }
    }I tried to print out the username and passwords to the indexes of 0, 1, and 2, and they're all the same.
    System.out.println(accounts.get(0).username);
    System.out.println(accounts.get(0).password);
    System.out.println(accounts.get(1).username);
    System.out.println(accounts.get(1).password);
    System.out.println(accounts.get(2).username);
    System.out.println(accounts.get(2).password);What is also interesting, is that it only fetched (or copied) the last two lines in the text document. It ignores all the entries before that.
    Do you know what I did wrong? I think I did a logic error in there somewhere.

  • Barcode scanner input

    Hi .
    I have an application that needs to receive bar code scanner input (the DS6707 from motorola). This application also discusses with 3 or 4 boards that run in parallel (using serial port com). So I have at least 5 threads that are running in parallel: one for each port com, one supervisor, and the main for the user interface.
    I created a control to get the data coming from the barcode scanner, but sometimes I lose some number on my barcode, or sometimes I receive ‘?’ instead of a number.
    If I create a thread that read the standard input, it works, I always receive all my numbers, but the problem is that I have the standard input that is visible and I don’t want.
    I tried to used keyboard methods from the windows library , but I don’t know how to proceed.
    Thanks for your help.

    I have a question about a keyboard wedge scanner input.
    I have a single panel with several text boxes placed in a grid.
    I post the output from 8 flash programmers in the boxes.
    I have a single wide text box below these to display general program status.
    My problem is when I scan the barcodes from the panel array, all data goes
    through the Upper Left text box. i want the data to go through the big box on the bottom.
    The reason I am using the text box in the upper left, is because that is where the data went
    when I scanned the bar codes. I was desperate to get the project moving forward.
    And the StdIO window caused too many problems.
    Question,  How do I move the cursor to the other text box ? I have tried many Set / Get
    Attribute parameters.  If there exists any "how-To" example code I would be grateful.
    void ReadSerialNumber1 (char* BigBuffer9)
     statspanelHandle  = TESTER_DialogGetSubPanelCVIHandle(&StatsHandle);
     statspanelHandle  = GetCtrlVal (StatsHandle, STATSPANEL_TEXTBOX_2, BigBuffer9);
     DisplayPanel(StatsHandle);
     fprintf(Stream1,"Serial Number..~%s~\n",BigBuffer9);
    code in main section
      sprintf(LittleBuffer1,"\n  -- SCAN Serial Number Nest 1-- ");
      WriteTextBox1(LittleBuffer1);
      PN_Size = strlen(LittleBuffer1);
      for(x=0;x<128;x++){ LittleBuffer1[x] = '\0';}
      PN_Size = strlen(LittleBuffer1);
      while(PN_Size != 10){
         int Stat_Val;
         Delay(0.5);  
      ReadSerialNumber1(LittleBuffer1);
         PN_Size = strlen(LittleBuffer1);
      if(TEST_CHECK_BREAK) break;
      if(PN_Size == 10)  Ready_Go = 1;
      strcpy(sSerialNum1,LittleBuffer1);
      strcpy(Scan_Buffer[0],LittleBuffer1);
      if(!strcmp(ModuleType2,"DSM")) strcpy(Scan_Buffer[1],LittleBuffer1);
      ResetTextBox2();
      if(TEST_CHECK_BREAK) break;
      sprintf(LittleBuffer1,"____%s____",Scan_Buffer[0]);  
      WriteTextBox1(LittleBuffer1); 
      Ready_Go = 0;

  • Scanner Input from File

    I'm trying to read from an external file using the Scanner class and to store the input in the applicable arrays, but I don't know how to skip lines.
    For example, if a text file has this in it:
    Name: Bob
    Age: 30
    Job: Engineer
    Name: Joe
    Age: 40
    Job: ManagerIt reads fine, and stores fine. But, if I have this instead:
    Name: Bob
    Age: 30
    Job: Engineer
    Name: Joe
    Age: 40
    Job: ManagerWith the empty line, the String class throws an index out of range exception. Same goes for if the very first line of the file is also blank.
    Here is my code:
    String[] name = new String[100];
    int[] age = new int[1000];
    String[] job= new String[1000];
         try {
                  Scanner input = new Scanner(new BufferedReader(new FileReader("test.txt")));
                  for (int i = 0; input.hasNext(); i++) {
                       name[i] = input.nextLine().substring(6);
                       age[i] = Integer.parseInt(input.nextLine().substring(5));
                       job[i] = input.nextLine().substring(5);
                       System.out.println("Name: " + name);
                   System.out.println("Age: " + age[i]);
                   System.out.println("Job: " + job[i]);
              input.close();
         } catch (FileNotFoundException error) {}Thank you all very much!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I already have something else that is handling non-existent files, so I don't need to do anything there.
    And thank you very much, I figured out how to do it! I just needed to temporarily store the line, see if it was longer than 1 in length, and perform based on that.
    Thank you very much!
    Edited by: ManiKatti on Dec 31, 2009 7:14 PM

  • 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

  • Scanner input error

    I want to make a very simple program that allows the user to enter a key/character and have the corresponding unicode value returned. The problem is that I receive an error after the input of any character.
    Here is the code:
    import java.util.Scanner;
    public class KeyMap
    public static void main (String args[])
    int number; //the future unicode value.
              System.out.print ("Enter the key you want the unicode number of: ");
              Scanner scan = new Scanner (System.in);
              number = scan.nextInt();
              char key = (char)number;
              System.out.print ("The number for key " + key + " is " + number);
    And I get this error in the run log after the character is entered:
    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 KeyMap.main(KeyMap.java:11)
    KeyMap has exited with status 1.
    Thanks for any help!

    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 KeyMap.main(KeyMap.java:11)Well that's coz your listening for an Integer input.
    the error should happen if you input non-integer data type.
    Nywled

  • Scanner Input Validation

    Hi, I hope Im posting to the right place.
    I want to check to see if the user input is an integer and keep asking for one if the input is not an integer. Should be very simple but I cant do it because I just dont know how. Im not willing to use a "try and catch" since I dont know how to use that either.
    This is what I got...
         int num;
         System.out.print("Please enter a number? ");
         Scanner sc = new Scanner(System.in);
         while (!sc.hasNextInt())
              System.out.println("That is NOT an Integer!");
              System.out.print("Please enter a number? ");
         num = sc.nextInt();
         System.out.println(num + " is an Integer!");Thank you...

    This is what I did in a recent project(I use BufferedReader, not Scanner). There are actually quite a few ways to do it. You can check the each char to see if they are between 0-9, but a try/catch right in main but I found this to be most effective to keep the program running. It's not the fastest running time from what I've tried(checking each char to be 0-9 was probably fastest) but if you want full proof do something like this.
    public class Test{
         public static boolean isInteger(String string){
              try{
                   Integer.parseInt(string);
                   return true;
              catch(NumberFormatException nfe){
                   return false;
               public static void main(String[] args){
                    String input;
                    int n;
                    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              //gets the number of students to input
              System.out.println("How many students are there?");
              try{
                   input = in.readLine();
              catch (IOException ioe){
                   System.out.println("IO error trying to read input");
                       System.exit(1);
                   while(!isInteger(input) || input.equals("")){
                      System.out.println("Not a number, please input a number");
                   try{
                        input = in.readLine();
                   catch (IOException ioe){
                        System.out.println("IO error trying to read input");
                            System.exit(1);
                 n = Integer.parseInt(input);

  • Adobe form barcode scanner input

    I made an Adobe form with X Pro.  The purpose of the form is to inventory equipment.  I use a barcode scanner to enter serial numbers into the form.  When I scan the barcode (Code 39) of an item the serial number entered into the form is truncated.  To ensure that the scanner was reading the barcode correctly I scanned a code while having notepad open, it input the entire serial number correctly.  I did the same thing with Word and the serial was also input correctly.  Why is the form truncating my serial number?  I can type more in the field if I so wish so I know that a character limit is not the issue.  I checked all of the text box's properties but see nothing incorrect or limiting. 
    Thanks for the help,
    Goob

    Sorry for never replying to your post.  The problem is: I do not know why this is happening.
    Your last sentence "on the Text Area the scan seems to stop before entering all digits but when I scroll back through, they are accurate" makes me think.  As I wrote earlier, "A barcode scanner is basically just an input device like a keyboard", but very much faster.  Somehow it seems that the software acts like it is encountering the carriage return before all the data digits have been processed.
    But somehow it also seems to correct itself in a text area that allows multiple lines, but not in a single-line text field.
    Yet that does not happen with my barcode scanner, but with yours and the o/p's.
    Very confusing!  Does anybody else have some thoughts on this?

  • Scanner input from other class

    i have the following scanner class
    import java.util.Scanner;
    public class Input {
       // Prompted input of an int
       public static int getInt( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           int result = in.nextInt();
           return result;
       // Prompted input of a float
       public static float getFloat( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           float result = in.nextFloat();
           return result;
       // Prompted input of a word/token
       public static String getToken( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           String result = in.next();
           return result;
    however i want to edit the code to get the following things from a different class to be displayed when run.
    String name = cname.getText();
    int length = Integer.parseInt(length.getText());
    any ideas on how to do this

    Edit: Nevermind. I guess for the prompts.
    ANY-who...
    float f = Input.getFloat(/*prompt string */);
    String s = Input.getText(/* prompt string */);
    Input. ...etc.
    Message was edited by:
    jGardner

  • Scanner input  VS keyboard input

    Dear all,
    We have a webdynpro application that receives it's input from a usb barcode scanner. The screens are working fine, but now there's an extra requirement, that for some input fields, it's mandatory that the input is coming from the scanner, and not from manual input with the keyboard.
    Is it possible?
    The barcode scanner behaves as an input device, without triggering events or so, so at this moment, we don't really know if the input is coming from a scanned barcode or from manual input with the keyboard.
    Kind regards,
    J.
    PS: the scenario is where the web dynpro application runs on a desktop or laptop, so the alternative for handheld with barcodereader UIElement is not an option to solve this.

    Hi
    Please explain this point again :  the scenario is where the web dynpro application runs on a desktop or laptop, so the alternative for handheld with barcodereader UIElement is not an option to solve this.
    With external hardware device(Thumb print reader , Signature pad  ) it has set of API which we  can incorporate inside our application , challenging part is whether
    such sort of solution is there in webdynpro or not , alternatively we can use JSP with java script to handle this  with using IFRAME UI (which is deprecated) or webwidgetUI element (might available in 7.2 ).
    further with your point
    The barcode scanner behaves as an input device : Yes by default is get its place to write , we have to highlight that input field with current cursor position.
    Hope you get some help?
    Best Regards
    Satish Kumar

  • Satellite A200/W00 - Fingerprint Scanner not being recognised by software

    Hi.
    I'm running a Satellite A200/W00 Toshiba laptop (PSAF6A-0W00IN), and I just recently installed my brand new Windows 7 Professional that I just bought.
    I found the Windows 7 Drivers for my laptop on the website and installed the Protector Suite QL 5.8.0.4024, and it installed just fine.
    Once I restart my computer after installing, on the login screen where the fingerprint scanner button is to log in it says 'Cannot read scanning device', or something along those lines.
    When I log in there is another pop-up with the program on the task bar stating the same thing, that my fingerprint scanning device needs to be plugged in. It's built into the laptop, it shouldn't need 'plugging in'.
    I tried uninstalling the drivers for my Biometric device, and then on scanning for hardware changes it immediately detected my Fingerprint scanner again and reinstalled the drivers from it.
    So, my Fingerprint scanner is clearly working, but Protector Suite QL isn't detecting it. I don't understand why.
    Anyone discovered this problem or know how to fix it? I can't exactly check the state of my scanner as it is built into my laptop.

    I'm not sure what the TrueSuite Access Manager you mentioned is. If that is the program that you use for managing your fingerprints/logging in with fingerprint reader, then that is a different program than what I had come with my laptop.
    The program that came with my laptop for managing fingerprints and the reader is UPEK Protector Suite QL, and it used to work perfectly fine on Win7 RC and Vista Home Premium.
    I can't register my fingerprints at all as the program that is supposed to do it isn't finding my fingerprint reader. Logging in with the fingerprint reader is an option at the moment at the login screen, but as mentioned it says that it cannot find the reader.
    I have 'Fingerprint Login' selected in the settings with 'Allow to bypass logon using Windows password' and 'Allow user selfenroll in login', and other settings are set to 'Convenient' mode.
    I've taken a screenshot of the exact popup that comes up whenever I try to access the Fingerprint reader to register/check storage, and have uploaded it. Here is a link: [http://img94.imageshack.us/img94/4880/fingerprinterror.jpg]

  • Scanner input question.

    I have an scanner which prompts the user to
    type some data into it.
    for example
    Lets say I have four strings.
    String id
    string name // this includes first and last name
    string address //this includes the full address.
    string price...
    When the first scanner prompts the user they type in
    DW123 and hits return
    the next scanner prompts the user to type i the name
    James Brown. and hits return.
    when this happens I will get the next scanner running together
    example
    enter your address==>,enter the price==>
    yet if I were to enter the name as JamesBrown it will work.
    is there away around this.
    any help would be great
    red

    Probably because you are calling the next method, which only returns a single token, not the nextLine method.
    Further, if you were to print out the address, I'm sure it would display "Brown".

  • Preferences Keep being forgotten - Corrupted?

    So every now and then the Finder will lose my View preferences and things will pop up in icon mode instead of list mode(this has happened on a folder that I use regularly and never change the view mode on - so no, it isn't that I opened a new window I never changed to 'list', or changed to 'icon' and forgot I did it).
    I used to ignore the View issue as it was rare, but now Mail is having issues remembering it's preferences. A couple of times it's reverted my Toolbar settings to the default when I open a new message window or make a reply.
    I'm going to delete my prefs for the Finder and Mail and see what happens, but the frequency of these issues is so low(about once every few weeks), that I won't trust it's resolved until I've had no issues for a couple months.
    Are my preferences corrupted, or is something else going on?
    On a potentially unrelated note, a number of times my system has forgotten I've left a window open on shutdown and it's not open anymore when I next startup. It sounds like it could be a PRAM issue, but my clock never resets when that happens, so I wonder if it might be related to the preference problem.

    Well, it's now forgotten that I had set the desktop arrangement as 'snap to grid'(after having deleted my preference files and reapplying my settings).
    This is getting annoying.

  • Password on encrypted volume not being "forgotten"

    I've set up an encrypted disk image (sparsebundle) and written a short bash script to simulate the old-style FileVault (to protect just a single account.)  It uses a folder within the encrypted volume as the home folder of an account that I use for sensitive information.  While it took a little while to get the permissions/ownership right on the volume and image, it works fine.  The other tricky part was that I have the script close the volume after it detects the account has been logged out -- I discovered I needed to wait a while for the logout to complete before closing the volume (otherwise it seemed like the system was trying to read or write from the volume even after "who" showed the account was logged out, and so it created a new home directory that confuses things.)  Now, the "problem" I have is this.  The first time the script opens the encrypted volume the system of course asks for the password.  Thereafter unless I reboot (logging in and out of the non-protected account I start the script from doesn't help) and possibly after a *long* time, tthe system seems to be remembering the password to the file -- on subsequent uses of the script the volume is opened without me being asked for the password.  I have examined carefully what I do when entering the password to make sure it's not saved in the keychain -- and indeed it isn't (verified by looking at the keychain).  Does anyone have any idea where the system (presumably the Finder) is saving the password and how to get it to "forget" it?  (I just realized I haven't checked to see if the password is "remembered" system-wide or just in the un-protected account.)  I've looked in both the system and account set of caches and nothing is obvious (all the finder cached data is in a single database, presumably in some obscure format.)
    Ted Lee
    Minnetonka, MN

    Some more experiments.  Since I was using the encrypted image to simulate FileVault, I put the image in the /User directory (which is where the old FileVault put its image for an account.)  This time I created another encrypted sparsebundle in a directory on my desktop -- the system did *not* remember the password for it (I had to enter it each time I opened it.)   More interestingly, diskutil *knew* about and remembered the image I'd put in /Users, but not the one on my desktop.  Diskutil even said that the volume inside it was an unmounted (encrypted) partition.   So it appears the system is "remembering" images that are in the /User directory -- I have no idea if there are other directories (say, /Library) where it would be remembered too.  But the "memory" has something to do with the live system -- since if I restart, the "memory" is lost.  Whether it is kept in some none-obvious place in the file system that disappears on shutdown or restart or just in virtual memory I of course don't know.

  • Scanner Input vs. Manually Keyed Input: Is there a way to tell?

    Is there an event, or other evidence, that can be seen in SAP logic debug, that can differentiate whether or not the input was keyed in, or entered from a handheld scanning device? Is there code that will give me this indicator I need to determine?
         Thank-You

    perhaps by create/change userid?  Can everyone scan with handheld device, or just some people, perhaps in a particular department ?

Maybe you are looking for