[英]Using scanner and a text file to get a certain string in a line
因此,我想让扫描仪分析文本文件的每一行,并在x个单词之后停止,在这种情况下,x = 3。
我的代码看起来像这样:
scannerName.nextLine();
scannerName.next();
scannerName.next();
scannerName.next();
好吧,这里的问题是nextLine()使扫描程序越过当前行AS WELL AS返回字符串。 因此,如果我调用next(),它将只找到下一行的下一个字符串(对吗?)。
有什么方法可以满足我的要求吗?
谢谢
请尝试以下代码:-while(scannerName.hasNext()!= null){
scannerName.next(); //Returns the 1st word in the line
scannerName.next(); //Returns the 2nd word in the line
scannerName.next(); //Returns the 3rd word in the line
//Analyze the word.
scannerName.nextLine();
}
您的问题不是那么精确,但是我有一个从txt文件读取的解决方案:
Scanner scan = null;
try {
scan = new Scanner(new File("fileName.txt"));
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " + ex.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
int wordsRead = 0;
int wordsToRead = 3; //== You can change this, to what you want...
boolean keepReading = true;
while (scan.hasNext() && keepReading) {
String currentString = scan.nextLine(); //== Save the entire line in a String-object
for (String word : currentString.split(" ")) {
System.out.println(word); //== Iterates over every single word - ACCESS TO EVERY WORD HAPPENS HERE
wordsRead++;
if (wordsRead == wordsToRead) {
keepReading = false; //== makes sure the while-loop will stop looping
break; //== breaks when your predefined limit is is reached
} //== if-end
} //== for-end
} //== while-end
有任何问题请告诉我:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.