2014-11-24 72 views
0

當我遇到了這個代碼的問題:未報告的異常java.io.IOException的編譯Java代碼

public class gravityv1 { 
    public static double[] calculategravity(double[] mass, int[] diameter) { 
     double[] gravity = new double[mass.length]; 

     for (int n = 0; n < mass.length; n++) { 
      gravity[n] = (6.67E-11 * mass[n])/Math.pow((diameter[n]/2), 2); 

     } 

     return gravity; 
    } 

    public static void print(double[] gravity, double[] mass, int[] diameter, String[] planet) { 
     System.out.println("       Planetary Data"); 
     System.out.println("Planet   Diameter(km)   Mass(kg)   g(m/s^2)"); 
     System.out.println("---------------------------------------------------------------------"); 
     for (int n = 0; n < planet.length; n++) 
     System.out.printf("%-7s%15d%20.3f%14.2f", planet[n], diameter[n], mass[n], gravity[n]); 
    } 

    public static void printFile(double[] gravity) throws IOException { 
     PrintWriter outFile = new PrintWriter(new File("gravity.txt")); 
     for (double gravita: gravity) { 
      outFile.println(gravita); 
     } 
     outFile.close(); 
    } 

    public static void main(String[] args) { 
     String[] planet = { 
      "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" 
     }; 
     double[] mass = {.330E24, 4.87E24, 5.97E24, 0.642E24, 1898E24, 568E24, 86.8E24, 102E24 
     }; 
     int[] diameter = { 
      4879, 12104, 12756, 6792, 142984, 120536, 51118, 49528 
     }; 

     double[] gravity = calculategravity(mass, diameter); 

     print(gravity, mass, diameter, planet); 
     printFile(gravity); 
    } 
} 

每當我嘗試編譯這段代碼,會出現一個錯誤,在「printFile(gravity)」,它位於底端。錯誤消息是:

未報告的異常java.io.IOException;必須被發現或被宣佈爲 。

我不知道該怎麼做。

回答

1

更改您的主要方法聲明:

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

在Java中,每一個方法的調用另一個方法B,必須申報所有B可拋出的異常
(除非它們是RuntimeException或後代除非A
捕獲並在try-catch塊中顯式處理它們)。

在你的情況A是main,B是printFile

1

你在你的main方法需要一個try-catch塊圍繞拋出IOException所有方法:

try { 
    printFile(gravity); 
} catch (IOException ex) { 
    // handle exception here 
} 

包括簽名後有throws IOException的所有方法。

相關問題