0

I am new to Java and I was looking to get a hold of a loop in java. I have the code below for trial and the problem is the for loop in the main method prints everything correct on the 1st iteration like this:

CMD>Please enter the name of person 1
CMD>ber
CMD>
CMD>sex of person1
CMD>male
CMD>
CMD>age of person1
CMD>23

but on the second iteration this happens

CMD>Please enter the name of person 2
CMD>sex of person2
CMD>

jumpes the first name enquiry the code is below

I have gone thru all trials and debugging

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

    person [] persons= new person[3];
    Scanner input= new Scanner(System.in);

        for (int i = 0; i <=2 ; i++) {

            persons[i]= new person();
            System.out.println(" Please enter the name of person " + (i+1));
            persons[i].P_name = input.nextLine();
            System.out.println(" sex of person" + (i+1));
            persons [i].P_sex= input.nextLine();
            System.out.println(" age of person" + (i+1));
            persons[i].P_age =input.nextInt();

        }
        ...

I want to input multiple names. there is a class person with

String P_name, P_sex;
int P_age; 

metho void P_data () 
  System.out.println(" The person named " + P_name + "is " + P_age + " years old and is a " + P_sex);
GhostCat
  • 127,190
  • 21
  • 146
  • 218
Bereket
  • 1
  • 1
  • Your question isn't fully clear, but I am guessing your problem is that last nextInt() ... you see, that only consumes the **number** you entered, but omits the ENTER that you typed for that line. – GhostCat Aug 09 '19 at 11:32
  • so what do i do? – Bereket Aug 09 '19 at 11:39
  • where is the link to the duplicate??? – Bereket Aug 09 '19 at 11:51
  • 1
    In that big yellow box on the top of the site that says "This question already has an answer here" – GhostCat Aug 09 '19 at 11:57
  • and unrelated: read about java naming conventions. You dont use "_" in variable names, unless for SOME_CONSTANT. Simply name those three fields like "name", "sex", "age". And your method should say what it does, for example: printPerson() ... and ideally, you rather override the toString() method in Person to return a nice string with those fields. So that you can simply do System.out.println(person) for example. – GhostCat Aug 09 '19 at 11:58

0 Answers0