简体   繁体   中英

countTokens() always returns 1 with user input

Before we begin, I don't believe this is a repeat question. I've read the question entitled StringTokenzer countTokens() returns 1 with any string , but that does not address the fact that a properly delimited string is counted correctly, but a properly delimited input is not.

When using the StringTokenizer class I've found that the countTokens method returns different outcomes depending on the whether the argument in countTokens was a defined String or a user defined String. For example, the following code prints the value 4.

String phrase = "Alpha bRaVo Charlie delta";

StringTokenizer token = new StringTokenizer(phrase);
//There's no need to specify the delimiter in the parameters, but I've tried
//both code examples with " " as the delimiter with identical results

int count = token.countTokens();

System.out.println(count);

But this code will print the value 1 when the user enters:Alpha bRaVo Charlie delta

Scanner in = new Scanner(System.in);

String phrase;

System.out.print("Enter a phrase: ");

phrase = in.next();

StringTokenizer token = new StringTokenizer(phrase);

int count = token.countTokens();

System.out.println(count);

使用in.nextLine()而不是in.next();

Scanner in = new Scanner(System.in);

String phrase;

System.out.print("Enter a phrase: ");

phrase = in.nextLine();

System.out.print(phrase);

StringTokenizer token = new StringTokenizer(phrase);

int count = token.countTokens();

System.out.println(count);

Print phrase and check that in.next() is returning "Alpha".

As suggested above, Use in.nextLine().

You could try using an InputStreamReader, instead of the Scanner:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String phrase = "";

System.out.print("Enter a phrase: ");

try {
    phrase = in.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

StringTokenizer token = new StringTokenizer(phrase);

int count = token.countTokens();

System.out.println(count);

nextLine() of Scanner also got the job done for me, though.

If you want the delimiter to be a space-character specifically, you might want to pass it to the constructor of StringTokenizer. It will use " \\t\\n\\r\\f" otherwise (which includes the space-character, but might not work as expected if eg the \\n-character is also present inside the phrase).

If you check the value of phrase , after invoking in.next() , you will see that's equal to "Alpha". By definition, Scanner's next() reads the next token .

Use in.nextLine() instead.

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