0

I've tried creating codes to solve a quadratic formula but I've only succeeded in creating it for a specific formula. Is there any way I can be providing the variables a, b, c by user input then the solution prints out? The program also refuses to run on command prompt but can run in eclipse. What might be the issue?

Here it is.

public class Equationsolver {

    public static void main(String[] args) {
    double a, b, c;
    a = 2;
    b = 6;
    c = 4;

    double disc = Math.pow(b,2) - 4*a*c;
    double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
    double soln2 = (-b - Math.sqrt(disc)) / (2*a);
    if (disc >= 0) {
        System.out.println("soln1 = " + soln1);
        System.out.println("soln2 = " + soln2);
    }else{
        System.out.println("equation has no real roots");
    }

    }

}
3
  • 1. did you compile? 2. did you add the directory with the .class files to the classpath? if either is false there is the issue Commented Mar 21, 2013 at 17:21
  • I've done all that. but my main issue is the user input for the variables. Right now I can only change the variables in the eclipse rather than in the output. Any suggestions? Commented Mar 21, 2013 at 17:26
  • This is just me being picky, but you should calculate disc THEN do a check on whether it's GEQ 0. If it is then calculate soln1 and soln2 and then print accordingly. You're doing unnecessary computations if disc is LT 0. Commented Mar 21, 2013 at 18:07

2 Answers 2

5

One possibility to take user input is to use the paramater String [] args. The String [] args contains the value pass to the program when you executed it like java -jar program.jar arg1 arg2 arg3.

In your case, you will need to check if the user pass 3 arguments to the program and if so then assigned thoses values to your variables.

Here is a little bit of code that might help, note that I didn't add the validation and you will need more validation to make sure that you sanitize the user input:

public class Equationsolver {

    public static void main(String[] args) {
    double a, b, c;
    a = Double.parseDouble(args[0]); //Here it will get the first argument pass to the program
    b = Double.parseDouble(args[1]); 
    c = Double.parseDouble(args[2]);

    double disc = Math.pow(b,2) - 4*a*c;
    double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
    double soln2 = (-b - Math.sqrt(disc)) / (2*a);
    if (disc >= 0) {
        System.out.println("soln1 = " + soln1);
        System.out.println("soln2 = " + soln2);
    }else{
        System.out.println("equation has no real roots");
    }

    }

}

EDIT: You will probably need to change your code to adapt to the fact that now a b and c might not be what you were thinking.

Sign up to request clarification or add additional context in comments.

Comments

3

You can take dynamic inputs from users in following way too

Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();

Comments