Vswe's Summer Courses | You're not logged in. Sign up or log in | Server time: | Donate
One can now see other persons' badge hunts. Simply head over to their profiles to access them.

Go back to sub forum page

General forum

Non-course related subjects

3. Programming help

problem with scanner

  • 2013-07-06 04:17:17
    lets say i want to get an integer then a line from a scanner and then print it out. so i do the following:

    Scanner myScanner = new Scanner(System.in);
    int test1 = myScanner.nextInt();
    String test2 = myScanner.nextLine();
    System.out.println("test1: " + test1 + " test2: " + test2);

    when i run that code, i have no problem with getting the integer. however, when i try to get a line, it didnt even ask me for an input and just gave me an empty string. i have to use nextLine() twice before it asks for an input and work properly.
  • 2013-07-06 07:12:02
    Its not nextLine() its hust next()
  • 2013-07-06 07:12:26
    *just
  • 2013-07-06 08:03:10
    No, nextLine() is correct to read a whole line, just next() returns only the next token (word). The problem is that myScanner.nextInt() reads the number on the current input line, but doesn't finish this line. That is, the line break is still in the input stream. Thus, when myScanner.nextLine() is called, it just reads the rest of this line (which is empty + the line break).

    My solution was exactly as yours: Just call nextLine() twice: Once to finish the current line, on which the number was, and then to read the next line.
  • 2013-07-06 09:24:35
    alright, thanks :)
  • 2013-09-29 07:01:43
    Thanks I had the same prob! C:
  • Log in or sign up to reply to this thread