2016-10-10 143 views
-5

我有一些代碼,當其在調用從另一個類的Java類

public static void main(String[] args) throws IOException { 

工作正常運行,但是當我改變代碼來讀取

public class Locate { 

    public Locate() throws IOException { 

,並從另一個類調用它使用

Locate location = new Locate(); 

我知道得到的錯誤

Exception in thread "main" java.lang.StackOverflowError 
    at geolocatenodes.Locate.<init>(Locate.java:26) 
    at geolocatenodes.Locate.<init>(Locate.java:28) 

調用另一個類的類的正確方法是什麼?

非常感謝

編輯:

public Locate() throws IOException { 

     Locate obj = new Locate(); 
     String file = "IP.txt"; 

     try (BufferedReader br = new BufferedReader(new FileReader(file))) { 
      String line; 
      while ((line = br.readLine()) != null) { 
//    System.out.println(line); 

       ServerLocation location = obj.getLocation(line); 
       System.out.println(location); 

       try { 
        String filename = "Locations.txt"; 
        try (FileWriter fw = new FileWriter(filename, true)) { 
         fw.write(location + "\n"); 
        } 
       } catch (IOException ioe) { 
        System.err.println("IOException: " + ioe.getMessage()); 
       } 
      } 
     } 
    } 
+1

你能告訴)全碼'公共的大括號內找到(拋出IOException異常{'? – Sweeper

+0

你的例外說明了一切!這是一個__StackOverflowError__。不是__IOException__。並且不要在構造函數中創建對象! –

+1

你需要去了解構造函數實際是什麼。 – user2357112

回答

0

讓我們用一些麪包店的比喻在這裏。想象一下,你想烤一些蛋糕,構造函數就像食譜,這是得到可用蛋糕的方式。用這個例子,你會想象這個食譜使用另一個蛋糕嗎?

回到您的代碼,您可以在您的Locate構造函數中使用而不是使用new Locate()

上構造一些閱讀:Providing Constructors for Your Classes