Java Scanner class reading strings?

Up vote 2 down vote favorite share g+ share fb share tw.

I got the following code: int nnames; String names; System.out. Print("How many names are you going to save: "); Scanner in = new Scanner(System. In); nnames = in.nextInt(); names = new Stringnnames; for (int I = 0; I Length; i++){ System.out.

Print("Type a name: "); namesi = in.next(); } System.out. Println(names0); When I run this code, the scanner will only pick up the first name and not the last name. And it will sometimes skip a line when trying to enter a name, it will show up as if I had left the name blank and skip to the next name.

I don't know what's causing this. I hope someone can help me! EDIT: I have tried in.nextLine(); it fixes the complete names but it still keeps a line, here is an example of the output: How many names are you going to save: 3 Type a name: Type a name: John Doe Type a name: John Lennon java string class duplicates java-util-scanner link|improve this question edited May 15 '11 at 12:51skaffman114k8135227 asked Sep 23 '09 at 13:28marcoamorales7917 100% accept rate.

Exact match of stackoverflow.com/questions/1466418/… – CPerkins Sep 23 '09 at 19:36.

Instead of: in.next(); Use: in.nextLine(); nextLine() reads the characters until it finds a new line character '\n.

Scanner. Next stops reading when it encounters a delimiter, which is a whitespace. Use the nextLine method instead.

After your initial nextInt(), there's still an empty newline in your input. So just add a nextLine() after your nextInt(), and then go into your loop: ... Scanner in = new Scanner(System. In); nnames = in.nextInt(); in.nextLine(); // gets rid of the newline after number-of-names names = new Stringnnames; for (int I = 0; I Length; i++){ System.out.

Print("Type a name: "); namesi = in.nextLine(); } ...

1 I've lost a programming contest recently because I used next() instead of nextLine() to skip that first \\n . That was so stupid :( – Denis Tulskiy Sep 23 '09 at 20:45 Was that CodeJam, by chance? I competed this year for the first time, and I got crushed - didn't even make it into round 2.

But I had fun in the qual and round 1, and I'll be back next year. – CPerkins Sep 24 '09 at 12:52.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions