0

I'm rather new to java and I am playing around with scanners. This is my code:

    System.out.print("Name? ");
    String name = s.nextLine();
    System.out.print("Height? ");
    double height = s.nextDouble();
    System.out.print("Haircolor? ");
    String haircolor = s.nextLine();
    System.out.print("Age? ");
    int age = s.nextInt();
    System.out.print("Job? ");
    String job = s.nextLine();

As you can probably see, I'm getting input about some person. Now the problem is that it gives an InoutMismatchException when I try to read the double. After reading this thread I changed that line to double height = Double.parseDouble(s.nextLine());. That works but now it doesn't stop after printing "Job? ". The program just goes on without reading anything.

Can anyone maybe tell me why that is? And also why I got this exception? I just suspected that a scanner maybe can't read different types (double, string, int) and can't "switch back" to String after having read an int. But that seems kinda odd.

Thank you so much in advance for an answer.

Tony

Community
  • 1
  • 1
tomet
  • 2,416
  • 6
  • 30
  • 45
  • I guess this class is reading about the scanner line by line. – Peter_James Nov 19 '13 at 14:06
  • Add another `nextLine` after `nextDouble` and after `nextInt`. – Maroun Nov 19 '13 at 14:14
  • Every other Javaquestion is about Scanner (the others about NullPointerException with unitialized array elements, string comparisions and ArrayOutOfBoundExceptions). What is it with this class that makes it so difficult? Is the API documentation somehow misguiding? (Just want to understand.) – Ingo Nov 19 '13 at 14:14
  • For me from the documentation it's not really clear how the individual methods (nextDouble, nextLine and so on) deal with \n. And when they are called. So e.g. is looks nextDouble() for a double once i hit return in the console? And I think a scanner is kinda one of the first things one learns when learning java. So it's lots of beginners. Because you just wanted to understand ;) – tomet Nov 19 '13 at 14:19

1 Answers1

1

try this..

        System.out.print("Name? ");
        String name = s.nextLine();
        System.out.print("Height? ");
        double height = s.nextDouble();
        s.nextLine();
        System.out.print("Haircolor? ");
        String haircolor = s.nextLine();
        System.out.print("Age? ");
        int age = s.nextInt();
        s.nextLine();
        System.out.print("Job? ");
        String job = s.nextLine();
subash
  • 3,116
  • 3
  • 18
  • 22