2016-07-22 90 views
1

在我们开始之前,我不认为这是一个重复的问题。我已阅读题为StringTokenzer countTokens() returns 1 with any string的问题,但这并没有解决正确定界的字符串被正确计数的事实,但正确定界的输入不是。countTokens()总是返回1与用户输入

当使用StringTokenizer类时,我发现countTokens方法返回不同的结果,具体取决于countTokens中的参数是定义的String还是用户定义的String。例如,下面的代码打印值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); 

但是当用户进入该代码将打印的值1:阿尔法BRAVO查理增量

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); 
+0

Just throwong this out(from [docs](https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html)):“* StringTokenizer是一个遗留类这是为了兼容性原因保留的,尽管**在新代码中不鼓励使用它***“。可能想考虑使用'String#split(String)' –

+0

我很欣赏输入,但我需要为类Assignment使用StringTokenizer类。 –

回答

3

使用in.nextLine()而不是在接下来的();

+0

这不起作用。 next()和nextLine()都接受字符串输入。只是为了确保我测试了它。不用找了。使用nextLine()也会引入键盘缓冲区问题。 –

+1

它对我来说非常好。 Scanner in = new Scanner(System.in); 字符串短语; phrase = in.nextLine(); StringTokenizer token = new StringTokenizer(phrase); int count = token.countTokens(); System.out.println(count); 运行: 阿尔法bRaVo查理德尔塔建立成功(总时间:19秒) – beatrice

+0

@CraigK。不同之处在于next()遇到空间时会中断。 'nextLine()'不是 –

0

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);

打印短语并检查in.next()是否返回“Alpha”。

如上所示,使用in.nextLine()。

0

你可以尝试使用一个InputStreamReader,而不是扫描仪:

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扫描仪()也得到了这份工作为我做的,虽然。

如果您希望分隔符是空格字符,您可能希望将它传递给StringTokenizer的构造函数。否则它将使用“\ t \ n \ r \ f”(其中包括空格字符,但如果例如\ n字符也出现在短语中)可能无法按预期工作。

0

如果您检查phrase的值,在调用in.next()后,您会看到等于“Alpha”。根据定义,扫描仪的next()读取下一个标记

改为使用in.nextLine()

+0

我测试了你的建议,现在我看到了next()和nextLine()之间的区别,但是当我在我的特定应用程序中使用nextLine()时,程序不允许用户输入字符串,程序结束。我想我可以尝试一个while循环使用hasNext并保持一个累加器。 –

+0

由于我的IDE,我以前有使用扫描仪读取输入的类似问题。你在使用IDE吗?尝试在命令行上运行你的程序。 – Kyriakos

+0

我的IDE确实是越野车,我已经解决了这个问题。 –