Java:扫描仪停在新线上 [英] Java: Scanner stopping at new line
问题描述
我正在尝试扫描文本文件并将它们添加到地图中,地图和一切正常。 但是,当涉及到文本文件中的输入或空白行时,扫描程序似乎停止了。这是我的问题
I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a 'enter' in the text file, or a blank line. This is my problem
这是我的扫描仪/映射器代码块
here is my block of code for the scanner/mapper
class OneButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent evt)
{
final JFileChooser oneFC = new JFileChooser();
oneFC.showOpenDialog(AnalysisFrame.this);
String newLine = null;
oneFC.getName(null);
int returnVal = 0;
File fileOne = oneFC.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(fileOne);
}
catch (FileNotFoundException ex) {
Logger.getLogger(AnalysisFrame.class.getName()).log(Level.SEVERE, null,
ex);
}
inputText = input.nextLine();
String[] words = inputText.split("[ \n\t\r,.;:!?(){}]");
for(int i = 0; i < words.length; i++){
key = words[i].toLowerCase();
if (words[i].length() > 1){
if (mapOne.get(key) == null){
mapOne.put(key, 1);
}
else {
value1 = mapOne.get(key).intValue();
value1++;
apOne.put(key, value1);
}
}
}
}
}
感谢您的帮助!
推荐答案
您应该在循环内扫描,直到它到达文件的末尾,示例:
You should scan inside a loop until it reaches the end of the file, for example:
StringBuilder builder = new StringBuilder();
while(input.hasNextLine()){
builder.append(input.nextLine());
builder.append(" "); // might not be necessary
}
String inputText = builder.toString();
使用 split
的替代方法可能是使用分隔符,使用扫描程序
并使用 hasNext()
和 next()
而不是 hasNextLine()
和 nextLine()
。尝试一下,看看它是否有效。
An alternative to using split
could be to use a Delimiter with the Scanner
and use hasNext()
and next()
instead of hasNextLine()
and nextLine()
. Try it out, see if it works.
例如:
scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
ArrayList<String> tokens = new ArrayList<String>();
while(scanner.hasNext()){
tokens.add(scanner.next());
}
String[] words = tokens.toArray(new String[0]); // optional
另外在旁注中,没有必要创建 JFileChooser
每次:
Also on a side note, it's not necessary to create the JFileChooser
everytime:
class OneButtonListener implements ActionListener
{
private final JFileChooser oneFC = new JFileChooser();
@Override
public void actionPerformed(ActionEvent evt)
{
这篇关于Java:扫描仪停在新线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!