Good day!
I was wondering why my input skips on the second loop on my array. I'm really confused since my code looks good at first loop. Hope somebody can help me on this matter... THanks in advance.. Pls view my attached file... thanks :)
Printable View
Good day!
I was wondering why my input skips on the second loop on my array. I'm really confused since my code looks good at first loop. Hope somebody can help me on this matter... THanks in advance.. Pls view my attached file... thanks :)
Hi kryptonite03, welcome.
It's better to actually post the code so everyone can get at it easily. There's a code button you can use for that. Or put [CODE] at the start of your code and [/CODE] at the end.
I'll post it here so I can read it...
Code:import java.util.Scanner;
public class ArrraySample {
public static void main(String[] args) {
String[] lastname = new String [10];
String[] firstname = new String [10];
int []age = new int [10];
Scanner input = new Scanner (System.in);
int n = 0;
for (n = 0; n < 3; n++)
{
System.out.println("Input no" + (n + 1));
System.out.println("Enter last name");
lastname[n] = input.nextLine();
System.out.println("Enter first name");
firstname[n] = input.nextLine();
System.out.println("Enter age");
age[n] = input.nextInt();
}
for (n = 0; n < 3; n++)
{
System.out.println("Lastname \t\t Firstname \t\t Age" );
System.out.println(lastname[n] + "\t\t" + firstname[n] + "\t\t" + age[n]);
}
}
}
Code:age[n] = input.nextInt();
This line could cause problems because nextInt() reads (and returns) an integer from the input stream. But it leaves the current position in the stream just before the newline. What this means is that next time you call nextLine() you will get an empty string returned.
One way to avoid this is to call nextLine() immediately after nextInt() and do nothing with the empty string it returns.
Code:for (n = 0; n < 3; n++)
{
System.out.println("Input no" + (n + 1));
System.out.println("Enter last name");
lastname[n] = input.nextLine();
System.out.println("Enter first name");
firstname[n] = input.nextLine();
System.out.println("Enter age");
age[n] = input.nextInt();
[b]input.nextLine();[/b]
}
Good day! My apologies for not posting the codes...
pbrockway2, Thank you very much for guiding me.. Im really new to Java.. The input.nextLine(); statment works well!
You're welcome.