繁体   English   中英

带有用户输入的二次公式(Java)

[英]Quadratic Formula With User Input (Java)

我是编码方面的新手,我不太确定如何100%写出这个问题。 我试图弄清楚为什么我的程序只存储值“ a”的第一个输入,即使该数字为负数也是如此。

例如:a = -1(值必须大于0。再次输入值'a':) a = 1 b = 3 c = -4

因此,在程序编译时,仅存储了“ a”(-1)的第一个值,而不存储第二个值(1),并且在遇到第二个if代码块时终止了程序。 我完全不知道如何解决这个问题:/

这是我的代码:

package quadratic;

import java.util.*;

//Program that does quadratic equations
public class Quadratic{
    public static void main(String[] args){

        boolean run = true;
        while(run){ //if program completes true, will start program again
            Scanner sc = new Scanner(System.in); // set scanner to allow user input

            System.out.println("Please enter value for 'a':");
            double a = (sc.nextDouble()); //looking for user input
            if (a <= 0){
                System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
                sc.nextDouble(); //prompt user again if value less than or equal to 0
            }
            System.out.println("Please enter value for 'b':");
            double b = (sc.nextDouble());
            System.out.println("Please enter value for 'c':");
            double c = (sc.nextDouble());
            System.out.printf("Values entered: a:%s b:%s c:%s \n",a,b,c);

            if (Math.pow(b,2)- (4 * a * c) <= 0){
                System.out.println("Impossible. Program Terminating");
                System.exit(0); //Terminate program
            }

            double qf1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
            double qf2 = (-b - Math.sqrt(Math.pow(b, 2) -(4 * a * c)))/ (2 * a);
            // qf stands for Quadratic Formula
            System.out.printf("Anwser One: %s \n", qf1); //%s whatever qf1 returned
            System.out.printf("Anwser Two: %s \n", qf2); //%s whatever qf2 returned
        }
    }
}

你只是打电话

sc.nextDouble(); //prompt user again if value less than or equal to 0

a = sc.nextDouble(); //prompt user again if value less than or equal to 0

所以,您只是丢掉第二个数字

此外,您可以第二次输入负数,因为您无需检查该数字是否小于零(提示:可能是循环,直到输入了有效的a值?)

 if (a <= 0){
    System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
    sc.nextDouble(); //prompt user again if value less than or equal to 0
    }

将上面的代码替换为:

 if (a <= 0){
    System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
    a = sc.nextDouble(); //prompt user again if value less than or equal to 0
    }

另外 ,您应该使用循环而不是if语句,例如:

 while (a <= 0){
    System.out.print("Value must be greater than 0. Enter value 'a' again:\n");
    a = sc.nextDouble(); //prompt user again if value less than or equal to 0
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM