Finding Variables from a String

124 views Asked by At

I have been working on a project to find the roots and discriminant from an entered quadratic equation in standard form. I have hit a roadblock trying to pull the coefficients from the equation. I think I am all set locating the positions of the coefficients (A,B,C), but I am having trouble getting the actual numbers out of the user input. (The last block of code is for the CoeffA int which I am trying to find. I left of CoeffB and CoeffC to save space here.) Any help or tips in cleaning up my code and extracting the coefficient from the user input would be much appreciated. I have been having a lot of trouble with strings. Thanks

import java.math.*;
import java.util.Scanner;

public class QuadProject2{
    public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
        int CoeffA=0;
        int CoeffB=0;
        int CoeffC=0;
        double root1;
        double root2;
        double disc;
        double root1new;
        double root2new;
        final String SENTINEL = "quit";
        do{
            System.out.println("Enter a quadratic equation in standard form");
            String quad=sc.nextLine();
        if(quad.equals("quit")){
            break;
        }
        while (!quad.equals((SENTINEL)));

        if(quad != "quit" || quad == "0"){
            **int pos = quad.indexOf("x"); 
            int pos2 = quad.indexOf("x", pos);
            int pos3 = quad.indexOf("=");
            //This should extract the a,b,and c coefficients from the user entry
          *int CoeffA=(0,pos);*
            if(CoeffA>0){
                double a=Double.parseDouble(CoeffA);
            }
            if(CoeffA==0){
                return int 1;
            }
            if(CoeffA<0){
                return int -1;
            }****
1

There are 1 answers

0
hfontanez On

In my opinion:

System.out.println("Enter a quadratic equation in standard form");
String quad=sc.nextLine();

Would be a lot better as:

System.out.print("Enter a quadratic equation coefficients (separated by spaces): ");
double a=sc.nextDouble();
double b=sc.nextDouble();
double c=sc.nextDouble();

This way, you don't have to convert a string input to a number. It is all done for you. If you want to loop, that is fine. However, before attempting to loop, make sure it works for a single iteration. Make sure you add sufficient handling of non-numeric values, etc.