user84871
user84871

Reputation:

user input to create java program

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");
    }

    }

}

Upvotes: 0

Views: 221

Answers (2)

Siba Prasad Patro
Siba Prasad Patro

Reputation: 35

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

Upvotes: 3

Marc-Andre
Marc-Andre

Reputation: 912

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.

Upvotes: 5

Related Questions