【问题标题】:Using scanner and a text file to get a certain string in a line使用扫描仪和文本文件在一行中获取某个字符串
【发布时间】:2014-09-28 11:29:13
【问题描述】:

所以我希望扫描仪分析文本文件的每一行并在 x 字数后停止,在本例中为 x=3。

我的代码看起来像这样:

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

好吧,这里的问题是 nextLine() 将扫描仪推进到当前行之外,并且返回一个字符串。因此,如果我调用 next(),那只会找到下一行的下一个字符串(对吗?)。

有没有办法按照我的要求去做?

谢谢

【问题讨论】:

    标签: java


    【解决方案1】:

    试试下面的代码:- 而(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();
    

    }

    【讨论】:

      【解决方案2】:

      您的问题不是那么精确,但我有一个从 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
      

      如果您有任何问题,请告诉我 :-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        • 2013-07-21
        相关资源
        最近更新 更多