【发布时间】:2020-09-14 02:13:15
【问题描述】:
我试图弄清楚我是否可以计算每个令牌的字符并显示该信息,例如:
day 被标记,我的输出将是:“Day 有 3 个字符。”并继续为每个令牌执行此操作。
我最后一次打印出每个令牌中的字符数的循环永远不会打印:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
控制台示例:
请输入一个至少包含 4 个单词,最多 8 个单词的句子:
你好,这是一个测试
谢谢。
您输入了:
你好,这是一个测试
句子中的每个单词都是:[Hello, there, this, is, a, test]
【问题讨论】:
-
编译器或你的IDE告诉你你的代码是否编译。如果没有,他们会给你错误信息?!
-
但如果没有真正的minimal reproducible example,我们真的无法判断...
-
@GhostCat 抱歉,我不清楚。我没有收到错误消息,但没有得到我想要打印到控制台的信息。我会用一个例子来更新我的问题。
标签: java arraylist char tokenize stringtokenizer