• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why my Array skips the first entry ?

 
Ittai Cohen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all
this is my first post here (I am a very new Java user !)

I wrote a small program in order to practice arrays and objects (= and array of objects). it asks the user to enter a few words & their defenition, and then it shows them/ later it will examine the user.
I made a loop in which the user has to enter word & defention x times. however, at the first run of the loop, [i=0] the array skips the first entry (word) and enter the keyboard input into
the wrong field (defention), or skips directly to ask for that value (defention), without changing the "word". when index loop =1 it is ok.

I would like to learn from this what am I doing wrong.

So thank you so much!
You are amazing!





[Edit - fixed line breaks - MB]
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The nextInt() just takes the number and leaves the token at the end which makes the nextLine() to skip user input.

Here's a sample problem and a possible solution of putting a dummy nextLine() after the nextInt().




You can try something similar in your code like below

 
Andriy Olenchenko
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First
it is not sense. Use Second read only int in line, but not line. You still have characters in line '\n' and when you try read by code you read '\n'. You can use next code
 
Ittai Cohen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much. That worked. I still try to understand why.
anyway, I'd spent hours on this problem (I am a real tyro -- who write java for only 2 weeks now).
I would like to expess my gratitude, that was very important and useful for me, save me many hours and encouraged me.
Best wishes

fixed code included ' a dummy':
x=str.nextInt();
str.nextLine();

[i still not sure about the 'this' word - since I wanted the input from the () = the Parameters or the to change the general, Class Variables.
So w [the word in the array[1] should get the input from the method = the Parameter w, that is this.w.
Probably I miss some point here, I will try to understand this important issue!

thank you
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To learn this keyword - http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic