簡體   English   中英

while循環不會讀取文件,也不會打印出java行

[英]while loop won't read file, or print out line java

我在下面的代碼中使用了hentAntall方法。 應該在txt文件中找到搜索詞。 我沒有任何錯誤。 它只是不會打印出任何兩個可能的行。

此方法必須首先訪問構造函數以獲取搜索詞,然后必須在txt文件中找到該搜索詞並添加計數。 構造函數從另一個類獲取搜索詞。 像這個新的lolz(“ searchword”)。hentAntall();

(對於該程序中的愚蠢命名,我深表歉意,但這只是我的一個程序的副本,我只是在嘗試糾正它而不用弄亂原來的名字。)

import java.io.File;
import java.util.Scanner;

public class lolz {

  private String sokeord=null;
  private int antall = 0;
  // Constructor
  lolz(String searchword) throws Exception{
    this.sokeord = searchword;
  }

  //toString method, to print in the same format.
  @Override
  public String toString(){
      return "\nSokeordet er: " + sokeord+ "\n";
  }

  // Gets the ammount of the searchword
  public int hentAntall() throws Exception{
    File file = new File("Hvorfor.txt");
    Scanner readfile = new Scanner(file);
    while (readfile.hasNextLine()){
           String nextline = readfile.nextLine();
            if (nextline.equalsIgnoreCase(sokeord)) {
            antall ++;
            System.out.println("Antallet av:" + sokeord + "er " + antall);
        }
        else {System.out.println("Error no such search word in the given text");}
    }
    return antall;
  }

  // void methode to increase the count of a searcheword.
  void oekAntall() {
    antall++;
  }
}

這是調用此方法的另一個類,並且也向構造函數提供信息。

public class Main {

public static void main(String[] args) throws Exception {
    new lolz("fungerer").hentAntall();

}}

還嘗試了一些建議,但它們沒有用,我只收到一條消息,進程退出代碼為0。

代替:

readfile.equals(sokeord)

這將比較Scanner類型的實例和String (永遠不會為true )。 您需要閱讀一行並進行比較。

String line = readfile.nextLine();
if(line.equals(sokeord)){

向您的班級添加一個主要方法:

public static void main(String[] args)
{
    hentAntall();
}

您將必須使hentAntall()靜態或創建lolz類的實例並以這種方式調用它。

同時更改:

while (readfile.hasNext()){
    if (readfile.nextLine().contains(sokeord)) {

您需要實際讀取輸入,然后檢查行中是否存在sokeord。

您的問題:

您正在嘗試將Scanner變量與String變量進行比較 ?!!!

說明

您嘗試比較掃描儀的內容是

java.util.Scanner [delimiters = \\ p {javaWhitespace} +] [position = 0] [match valid = true] [需要輸入= false] [源關閉= false] [跳過= false] [分組分隔符= \\,] [小數分隔符=。] [正前綴=] [負前綴= \\ Q- \\ E] [正后綴=] [負后綴=] [NaN字符串= \\Q \\ E] [無窮大字符串= \\Q∞\\ E ]

包含String變量的內容。


您沒有閱讀下面的每一行

if (readfile.equals(sokeord)) {

你應該有

 if (readfile.nextLine().equals(sokeord)) {

您的hentAntall方法應如下所示:

public int hentAntall() throws Exception {
    File file = new File("Hvorfor.txt");
    Scanner readfile = new Scanner(file);
    while (readfile.hasNextLine()) {
        String word = readfile.next();
        if (word.contains(sokeord)) {
            antall++;
            System.out.println("Antallet av:" + sokeord + "er " + antall);
        } else {
            System.out
                    .println("Error no such search word in the given text: ");
        }
    }
    readfile.close();
    return antall;
}

不要忘記關閉掃描儀資源,以免泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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