0

I am learning java and attempting to run this code:

import java.util.Scanner;

class Person {
    String name;
    int age;

}

public class MyClass {
    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    Person person1 = new Person();
    System.out.println("Input person1 age");
    person1.age = scan.nextInt();
    System.out.println("Input person1 name");
    person1.name = scan.nextLine();
    System.out.println(person1.name + " is " + person1.age);

    Person person2 = new Person();
    System.out.println("Input person2 age");
    person2.age = scan.nextInt();
    System.out.println("Input person2 name");
    person2.name = scan.nextLine();
    System.out.println(person2.name + " is " + person2.age);

    }
}

as i run the code i enter person1's age, but then it rushes past the prompt to enter person1's name and leaves it blank and returns " is 18" for example, and the same for the person2 input prompt. How would i format this code for it to run smoothly i can't figure it out and help would be much appreciated

Bennypea
  • 11
  • 4
  • use next() instead of nextLine() – SlumpA Dec 01 '16 at 13:33
  • `nextInt()` reads the int, and just the int, not the whole line. The input that remains is "\r\n" (or "\n"). So the call to `nextLine()` after `nextInt()` reads everything from the last position that was read (the end of the int) to the "\r\n", which is nothing. Either use `next()` or use `nextLine()` twice. – SlumpA Dec 01 '16 at 13:38

0 Answers0