• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trouble with array input  RSS feed

 
J P Wire
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's my code - The objective is to enter some basic info (age, name, gender) for x number of patients.




The issue I'm having is when the loop goes to the 2nd variable, i.e. I'm not able to enter a value for the name of the patient. It seems to skip taking the input there and goes directly to the next input, which is gender.


Any ideas as to why this is happening?
 
asr chowdary
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

This is problem with in.nextInt(); so add in.nextLine() after age[i] = in.nextInt(); this line

age[i] = in.nextInt();
in.nextLine();

It will work.


Thanks
 
asr chowdary
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Same example

public static void main(String[] args) {
System.out.println("welcome suresh : ");
String names[]=new String[2];
String gender[]=new String[2];
int age[]=new int[2];
Scanner scanIn = new Scanner(System.in);
for(int i=0;i<2;i++)
{
System.out.println("enter name"+(i+1));
names[i]=scanIn.nextLine();
System.out.println("enter gender"+(i+1));
gender[i]=scanIn.nextLine();
System.out.println("enter age"+(i+1));
age[i]=scanIn.nextInt();
scanIn.nextLine();


}
scanIn.close();
}
 
J P Wire
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Suresh,

Thank you for your response! Your solution seems easier than the one I implemented



Cheers!
 
Campbell Ritchie
Marshal
Posts: 56576
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

The nextInt() solution requires a Scanner, which was introduced in 2004 (Java5). I have never checked, but I think it does something similar to parseInt() in its nextInt() method.

You do realise that scanIn.close() in that situation can be very dangerous?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!