简体   繁体   中英

Java vector size()

I have a tutorial work based on vectors in java se. The task is to prompt the user to input ten words in a string and then we are supposed to split the words into single words and add each of them into a vector element. However, right at the beginning, I'm already facing problems with my codes. Right now, I even have problem finding out the size of the vectors so could you guys help me out here? Thanks!

import java.util.*;

class TenWords
{
public static void main (String [] args)
{
    Vector <String> words = new Vector <String>();

    Scanner userInput = new Scanner(System.in);
    System.out.println("Please enter ten words");

    String a;

    while(userInput.hasNext())
    {
        a = userInput.next();
        words.add(a);
        System.out.println(a);
    }

    int s = words.size();
    System.out.println(s);  
}
}

In this case userInput.hasNext() always returns true. So you need a finite loop. Use for loop

import java.util.Scanner;
import java.util.Vector;

public class TenWords {
    public static void main(String[] args) {
        Vector<String> words = new Vector<String>();

        Scanner userInput = new Scanner(System.in);
        System.out.println("Please enter ten words");

        String a;

        for (int i = 0; i < 10; i++) {
            a = userInput.next();
            words.add(a);
            System.out.println(a);
        }

        int s = words.size();
        System.out.println(s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM