Skip to content

Instantly share code, notes, and snippets.

@danleyb2
Last active August 29, 2015 14:16
Show Gist options
  • Save danleyb2/b6b7cc4feed5b4d1832c to your computer and use it in GitHub Desktop.
Save danleyb2/b6b7cc4feed5b4d1832c to your computer and use it in GitHub Desktop.
a simple command line program to solve quadratic equations
package main;
import java.util.Scanner;
public class solverQE {
static double A, B, C;
public static void main(String[] args) {
Scanner inpt = new Scanner(System.in);
System.out.println("Enter the equation to solve in this order> ax2+bx+c=0");
String equation =inpt.next().trim();
Abc(equation);
secondThird(equation);
solve(A,B,C);
//System.out.println("A:" +A+" B: "+B+" C: "+C);
}
static void Abc(String eqn) {
String a;
if (Character.isLetter(eqn.charAt(0))) {
a = "1";
} else {
a = String.valueOf(eqn.charAt(0));
for (int i = 1; i < eqn.length(); i++) {
if (Character.isLetter(eqn.charAt(i))) {
A = Double.parseDouble(a);
break;
} else {
a += String.valueOf(eqn.charAt(i));
}
}
}
A = Double.parseDouble(a);
}
static void secondThird(String eqn) {
int pos;
int singChB;
big:
for (int x = 0; x < eqn.length(); x++) {
if (eqn.charAt(x) == '+' || eqn.charAt(x) == '-') {
pos = x + 1;
if(eqn.charAt(x)=='-'){
singChB=-1;}
else {
singChB=1;
}
if (Character.isLetter(eqn.charAt(pos))) {
B = singChB;
break;
} else {
String b = String.valueOf(eqn.charAt(pos));
for (int j = pos + 1; j < eqn.length(); j++) {
if (Character.isLetter(eqn.charAt(j))) {
B = Double.parseDouble(String.valueOf(b))*singChB;
int signCh=j+1;
int gc = j + 2;
if (Character.isLetter(eqn.charAt(gc))) {
C = 1;
break;
} else {
String c = String.valueOf(eqn.charAt(gc));
for (int k = gc + 1; k < eqn.length(); k++) {
if (eqn.charAt(k) == '=') {
C = Double.parseDouble(String.valueOf(c));
break;
} else {
c += String.valueOf(eqn.charAt(k));
}
}
C = Double.parseDouble(String.valueOf(c));
if(eqn.charAt(signCh)=='-'){
C=(C*-1);
}
break big;
}
} else {
b += String.valueOf(eqn.charAt(j));
}
}
B = Double.parseDouble(String.valueOf(b))*singChB;
}
}
}
}
static void solve(double x,double y,double z){
double ans1,ans2;
double ru=(y*y)-(4*x*z);
ru=Math.sqrt(ru);
double rd=2*x;
ans1=((y*-1)+ru)/rd;
ans2=((y*-1)-ru)/rd;
printA(ans1,ans2);
}
static void printA(double a,double b){
//double ans1d,ans2d;
if((int)a==a&&(int)b==b) {
System.out.println("x1 is: "+(int)a+" and x2 is: "+(int)b);
return;
}
System.out.println("x1: "+a+" and x2: "+b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment