简体   繁体   English

使用扫描仪和文本文件在一行中获取特定字符串

[英]Using scanner and a text file to get a certain string in a line

So I want scanner to analyze each line of a text file and stop after an x amount of words, in this case x=3. 因此,我想让扫描仪分析文本文件的每一行,并在x个单词之后停止,在这种情况下,x = 3。

My code looks something like this : 我的代码看起来像这样:

    scannerName.nextLine();
    scannerName.next();
    scannerName.next();
    scannerName.next();

Well, the problem here is that nextLine() advances the scanner past the current line AS WELL AS return a string. 好吧,这里的问题是nextLine()使扫描程序越过当前行AS WELL AS返回字符串。 So if I call next(), that will just find the next string which is on the next line (right?). 因此,如果我调用next(),它将只找到下一行的下一个字符串(对吗?)。

Is there a way to do what I'm asking? 有什么方法可以满足我的要求吗?

Thank you 谢谢

Try the following code : - while(scannerName.hasNext() != null) { 请尝试以下代码:-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();

} }

Your question is not so precise, but i have a solution for reading from txt-files: 您的问题不是那么精确,但是我有一个从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

Let me know if you have any questions :-) 有任何问题请告诉我:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM