Java 使用扫描仪和文本文件获取行中的特定字符串
所以我想让扫描器分析文本文件的每一行,并在x个单词之后停止,在这个例子中x=3 我的代码如下所示:Java 使用扫描仪和文本文件获取行中的特定字符串,java,Java,所以我想让扫描器分析文本文件的每一行,并在x个单词之后停止,在这个例子中x=3 我的代码如下所示: scannerName.nextLine(); scannerName.next(); scannerName.next(); scannerName.next(); 好的,这里的问题是nextLine()使扫描器前进超过当前行并返回字符串。因此,如果我调用next(),它将只找到下一行上的下一个字符串(对吗?) 有没有办法做到我的要求 谢谢请尝试以下代码:- w
scannerName.nextLine();
scannerName.next();
scannerName.next();
scannerName.next();
好的,这里的问题是nextLine()使扫描器前进超过当前行并返回字符串。因此,如果我调用next(),它将只找到下一行上的下一个字符串(对吗?)
有没有办法做到我的要求
谢谢请尝试以下代码:-
while(scannerName.hasNext()!=null)
{
}您的问题不太准确,但我有一个从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
如果您有任何问题,请告诉我:-)
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