簡體   English   中英

使用掃描儀和文本文件在一行中獲取特定字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM