Question

I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:

public class Test{
private Vector<String> vecStr;

public void run(){
   vecStr = new Vector<String>();
   System.out.println("How many strings do you want for your string vector?");
   int numStr = keyboard.nextInt();
   System.out.println("Enter your string values.");
   for (int i=0;i<numStr;i++){
     System.out.println(i + "Input");
     vecStr.add(keyboard.nextLine());}
    }
  }
}

Let's say I input 4, somehow, the code gives me:

0
1
input:
2
input:
3
input:

It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?

Was it helpful?

Solution

Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.

OTHER TIPS

You can use input stream readers:

    Vector<String> vecStr = new Vector<String>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("How many strings do you want for your string vector?");
    int numStr = Integer.parseInt(reader.readLine());
    System.out.println("Enter your string values:");
    for (int i=0;i<numStr;i++){
        System.out.println(i + " Input: ");
        vecStr.add(reader.readLine());
    }
    System.out.println("vector contains:");
    System.out.println(vecStr);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top