java - 扫描器在 For 循环期间未完成
问题描述
我正在尝试编写一些代码来分析几段文本,但我发现扫描仪方法存在问题。这是我的相关代码:
public static void getInput(Scanner key) {
//This method takes the input of the user and makes it usable, controls all other methods, and prints findings
System.out.print("\nHow many pieces of text do you want to analyze? ");
int textNumb = key.nextInt();
for( int i = 1; i <= textNumb; i++) {
System.out.print("\nPlease enter text sample number " + i + ": ");
key.nextLine();
String textInput = key.nextLine();
System.out.print("text has been received\n"); //this does not print after first round
int sentences = getSentences(textInput);
int words = getWords(textInput);
int syllables = countSyllables(textInput);
printResults(sentences,words,syllables,textInput);
}
}
在第一轮 for 循环之后,扫描仪卡住并且程序完全暂停。如果我在第一轮后输入文本后再次按 Enter,则其余方法实际上都不会处理任何文本。在不关闭并重新打开扫描仪的情况下如何解决此问题?谢谢你。
解决方案
key.nextLine()
我假设在没有分配变量的情况下额外调用是因为您可能遇到了这里描述的问题: Scanner is skipping nextLine() after using next() or nextFoo()?
但是,在实施那里描述的解决方法时,您必须考虑到您正在使用循环。记住这一点,你只需要nextInt()
在循环之后和之后读取换行符一次,额外的没有意义nextLine()
。所以片段应该是:
int textNumb = key.nextInt();
key.nextLine(); // consume newline once, outside the loop
for (int i = 1; i <= textNumb; i++) {
System.out.print("\nPlease enter text sample number " + i + ": ");
String textInput = key.nextLine(); // read input inside the loop
...
}
推荐阅读
- regex - 在 main() 之前选择原型
- php - 调用未定义的方法 SQLite3::execute()
- javascript - 使用 React 管理 LTE 仪表板
- java - 在 Android Studio 中获取“Gradle 同步失败:连接重置”
- elixir - 使用 ExMachina 插入后是否可以不加载关联?
- c# - 更改 StringCollection 的排序
- neo4j - 密码多关系或两个节点之间关系的属性
- javascript - 在字母数字字符中的任何位置最多允许 2 位数字 javascript 正则表达式
- facebook - Facebook android app v 3.1没有获取出生日期和性别
- c++ - 将单个字符转换为 std::string 前置 \x01