-1

我的班级的 java 程序有问题。我必须创建一个程序,提示用户输入输出文件的路径和名称,该文件将包含我的程序将采用的方程的系数行,并使用二次公式计算解。到目前为止,我认为一切都是正确的,除了我的输出文件。假设我有一个包含 3 行系数的输入文件,我的程序将在控制台流中显示解决方案,但只会在输出文件中显示 1 行解决方案。

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();
4

1 回答 1

5

如果我正确地阅读了你的括号,那么问题是你在打电话

output.close();

在循环的每次迭代结束时。在编写完所有输出之后,您需要在循环之外调用它。

于 2013-10-29T20:31:46.803 回答