I'm creating a program for making shortcuts. Basically what it does is: I'm providing the number of words i want to process. Let's say I enter 3 in this case. The next step is to get those words from user by Scanner. Seems easy, right? What I've done? I put Scanner inside the loop (it should put the word inside ArrayList), but the loop is skipping the 0 without asking user for word. I think it's a problem with Scanner, cause when I put instead of scanner something like System.out.println the loop is working perfectly.
I already tried to make other function to ask user for word and add this element to list and in the same loop I'm just reaching this function. But it doesn't help. Also i tried moving the "i++" behind the data.add but doesn't work as well.
public class Main {
public static void main(String[] args) {
ArrayList<String> data = new ArrayList<>();
UserInteraction userInteraction = new UserInteraction();
userInteraction.enterData(data);
for(String x: data)
System.out.println(x);
}
}
public class UserInteraction {
private Scanner scanner = new Scanner(System.in);
private int getData() throws InputMismatchException {
try{
int number = scanner.nextInt();
return number;
}catch (InputMismatchException e){
System.out.println("Not a number. Try again:");
return getData();
}
}
void enterData(ArrayList<String> data){
System.out.println("Enter the number of words:");
int quantity = getData();
System.out.println("Now, enter the words. Every word must be separated by clicking enter:");
for(int i=0; i<quantity;i++){
System.out.println(i);
data.add(scanner.nextLine());
}
}
}
I'm getting this output:
Enter the number of words:
4
Now, enter the words. Every word must be seperated by clicking enter:
0
1
You can see that between 0 the Scanner is not reached for some reason. But after 1, 2 and 3 it work. Yes, I can just edit the loop changing i