2013-10-29 15 views
-1

我的Java程序對於我的課程有問題。我必須創建一個程序,提示用戶輸出文件的路徑和名稱,該文件將具有我的程序將採用的公式的係數行,並使用二次公式計算解。到目前爲止,我認爲除了我的輸出文件外,一切正常。假設我有一個包含3行係數的輸入文件,我的程序將在控制檯流中顯示解決方案,但僅在我的輸出文件中顯示1行解決方案。這是我第一次和我一起光顧的java課程!我在這裏先向您的幫助表示感謝!僅輸出一行代碼的Java程序

while (input.hasNext()) { 


    a = input.nextInt(); 
    b = input.nextInt(); 
    c = input.nextInt(); 

    discriminant = Math.pow(b, 2) - 4 * a * c; 
    ///There will be no solutions if discriminant<0 
    if (discriminant < 0){ 
     System.out.println("There are no solutions."); 
     output.println("There are no solutions."); 
    } 
    ///As with the above, if coefficent a = 0 no solutions 
    else if (a == 0){ 
     System.out.println("There are no solutions."); 
     output.println("There are no solutions."); 
    } 
    else if (discriminant == 0){ 
     solutionOne = (-b + Math.sqrt(discriminant))/(2 * a); 
     if (b < 0) { 
      System.out.printf("%3.0fx^2 %3.0fx + %3.0f, has one  solution:%5.3f%n",a,b,c,solutionOne); 
      output.printf("%3.0fx^2 %3.0fx + %3.0f has one solution:%5.3f%n",a,b,c,solutionOne); 
     } 
     else{ 
      System.out.printf("%3.0fx^2 %3.0fx + %3.0f has one solution:%5.3f%n",a,b,c,solutionOne); 
      output.printf("%3.0fx^2 %3.0fx + %3.0f has one solution:%5.3f%n",a,b,c,solutionOne); 
     } 

    } 
     else if(discriminant>0){ 
      solutionOne=(-b + Math.sqrt(discriminant))/(2*a); 
      twoSolutions=(-b - Math.sqrt(discriminant))/(2*a); 

      if(b<0){ 
       System.out.printf("%3.0fx^2 %3.0fx + %3.0f has two solutions: %5.3f %5.3f%n",a,b,c,solutionOne,twoSolutions); 
       output.printf("%3.0fx^2 %3.0fx + %3.0f has two solutions:5.3f %5.3f%n",a,b,c,solutionOne,twoSolutions); 
      } 

      else{ 

      System.out.printf("%3.0fx^2 %3.0fx + %3.0f has two solutions:%5.3f %5.3f%n",a,b,c,solutionOne,twoSolutions); 
      output.printf("%3.0fx^2 %3.0fx + %3.0f has two solutions: %5.3f%5.3f%n",a,b,c,solutionOne,twoSolutions); 
      } 

    } 

    output.close(); 

回答

5

如果我正確地讀你的斗拱,問題是,你在每次循環的末尾呼籲

output.close(); 

。在完成所有輸出後,您需要在循環的外部之外調用

+0

顯然是正確的答案。 –

相關問題