2012-04-02 88 views
0

當我嘗試創建一個可調用的類時,我似乎遇到了上述錯誤。我尋找了原因,但似乎無法找到任何東西。 NetBeans爲我提供了幾個選項來使事情變得抽象,但我對此很陌生,我寧願找出發生的原因。任何人都可以闡明這一點嗎?可調用的類給出錯誤:doPing不是抽象的,也不重寫抽象方法調用()?

public class doPing implements Callable<String>{ 

    public String call(String IPtoPing) throws Exception{ 

     String pingOutput = null; 

     //gets IP address and places into new IP object 
     InetAddress IPAddress = InetAddress.getByName(IPtoPing); 
     //finds if IP is reachable or not. a timeout timer of 3000 milliseconds is set. 
     //Results can vary depending on permissions so cmd method of doing this has also been added as backup 
     boolean reachable = IPAddress.isReachable(1400); 

     if (reachable){ 
       pingOutput = IPtoPing + " is reachable.\n"; 
     }else{ 
      //runs ping command once on the IP address in CMD 
      Process ping = Runtime.getRuntime().exec("ping " + IPtoPing + " -n 1 -w 300"); 
      //reads input from command line 
      BufferedReader in = new BufferedReader(new InputStreamReader(ping.getInputStream())); 
      String line; 
      int lineCount = 0; 
      while ((line = in.readLine()) != null) { 
       //increase line count to find part of command prompt output that we want 
       lineCount++; 
       //when line count is 3 print result 
       if (lineCount == 3){ 
        pingOutput = "Ping to " + IPtoPing + ": " + line + "\n"; 
       } 
      } 
     } 
     return pingOutput; 
    } 
} 

回答

2

在你的代碼中,call方法有一個參數:它不會覆蓋Callable接口的call方法 - 它應該是這樣的:

public String call() throws Exception{ //not public String call(String IPtoPing) 

} 

如果您使用的是Java 6+,最好不要使用Override註釋,它可以幫助找到錯誤的方法簽名(在這種情況下,您已經收到編譯錯誤):

@Override 
public String call() throws Exception{ 
} 
+0

感謝您的回覆:) – DMo 2012-04-03 11:57:19

1

您的'doPing'類定義爲implements Callable<String>。這意味着它應該實現call()方法不會採取任何參數。如果你想doPingCallable

public interface Callable<V> { 
    V call() throws Exception; 
} 

你將需要刪除String IPtoPing說法:

public class doPing implements Callable<String> { 
    // you need to define this method with no arguments to satisfy Callable 
    public String call() throws Exception { 
     ... 
    } 
    // this method does not satisfy Callable because of the IPtoPing argument 
    public String call(String IPtoPing) throws Exception { 
     ... 
    } 
} 
+0

感謝您的幫助。 – DMo 2012-04-03 11:56:59

1

Callable界面,您需要有一個call()方法下面是Callable定義。但是,您的方法是
call(String ipToPing)

考慮添加一個setIpToPing(String ip)方法來設置正確的IP。

I.e.

doPing myCallable = new doPing();//Note doPing should be called DoPing to keep in the java naming standards. 
myCallable.setIpToString(ip);//Simple setter which stores ip in myCallable 
myCallable.call(); 
+0

謝謝你。非常感激。 IPtoPing是我的主要方法在一個不同的類中的變量,所以我怎樣才能將這個變量傳遞給call()? – DMo 2012-04-03 11:56:27

+0

@ user1286779沒問題。我已經添加了一個例子。 – Jim 2012-04-03 12:42:02

相關問題