Results 1 to 5 of 5
Thread: Input skips on array
- 12-13-2010, 12:23 AM #1
Member
- Join Date
- Dec 2010
- Posts
- 18
- Rep Power
- 0
- 12-13-2010, 12:30 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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...
Java 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]); } } }
- 12-13-2010, 12:35 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Java 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.
Java 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] }
- 12-13-2010, 12:47 AM #4
Member
- Join Date
- Dec 2010
- Posts
- 18
- Rep Power
- 0
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!
- 12-13-2010, 12:48 AM #5
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Similar Threads
-
java skips a block of code...
By JavaSal in forum New To JavaReplies: 8Last Post: 02-07-2010, 09:58 AM -
Array Input
By Rose88 in forum New To JavaReplies: 2Last Post: 04-19-2009, 10:39 PM -
while loop skips code
By ejs7597 in forum New To JavaReplies: 3Last Post: 02-28-2009, 03:07 AM -
input placed in array
By smilejava in forum New To JavaReplies: 5Last Post: 11-12-2007, 07:29 AM -
input placed in array
By smilejava in forum New To JavaReplies: 1Last Post: 11-05-2007, 12:32 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks