我有一個hentAntall方法在我的代碼如下。它應該在txt文件中找到搜索詞。我沒有得到任何錯誤。它只是不會打印出任何兩條可能的線。while循環將不會讀取文件,或打印出行java
此方法必須首先訪問構造函數才能獲取搜索詞,然後必須在txt文件中找到該搜索詞並將其添加到計數中。構造函數從另一個類獲取搜索詞。像這樣new 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
告訴我們您的主類,並在調用該函數 – LeatherFace 2014-10-29 18:36:51
你永遠實際上讀什麼 – user2717954 2014-10-29 18:37:10
呀,這種方法是不是在你的代碼中調用.. – ryekayo 2014-10-29 18:37:25