Простой решатель квадратных уравнений

Я хотел создать простой решатель квадратного уравнения, но когда я запускаю его, он перехватывает первое выражение if каждой кнопки. Любые идеи?

public class MainActivity extends AppCompatActivity {
    Button button1, button2;
    String a_temp;
    EditText b_temp;
    EditText c_temp;
    TextView tv1, tv2;
    Double a,b,c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        });

        a_temp = ((EditText)findViewById(R.id.editText)).getText().toString();
        if (a_temp.equals("")) {
            a = Double.valueOf(0);
        } else {
            a = Double.valueOf(a_temp);
        }

        b_temp = (EditText)findViewById(R.id.editText2);
        if (!b_temp.getText().toString().equals("")) {
            b = Double.parseDouble(b_temp.getText().toString());
        }else {
            b = Double.valueOf(0);
        }

        c_temp = (EditText)findViewById(R.id.editText3);
            if (!c_temp.getText().toString().equals("")) {
            c = Double.parseDouble(c_temp.getText().toString());
        }else {
            c = Double.valueOf(0);
        }

        tv1 = (TextView) findViewById(R.id.textView2);
        tv2 = (TextView) findViewById(R.id.textView3);

        button1 = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (a == 0) {
                    tv1.setText("That's not a quadratic equation");
                }else {
                    if (b*b - 4*a*c < 0) {
                        tv1.setText("This quadratic equation has no real roots");
                    } else {
                        double root1 = (-b + Math.sqrt(Math.pow(b,2) - 4 * a * c))/(2*a);
                        double root2 = (-b - Math.sqrt(Math.pow(b,2) - 4 * a * c))/(2*a);
                        double result = Math.max(root1,root2);
                        tv1.setText(String.valueOf(result));
                    }
                }
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (a == 0) {
                    tv2.setText("That's not a quadratic equation");
                }else {
                    if (b * b - 4 * a * c < 0) {
                        tv2.setText("This quadratic equation has no real roots");
                    } else {
                        double root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                        double root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
                        double result = Math.min(root1, root2);
                        tv2.setText(" " + result);
                    }
                }
            };
        });
    }

XML-код:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Type the operands of the quadratic equation you want to solve"
    android:id="@+id/textView"
    android:layout_marginTop="39dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Root #1"
    android:id="@+id/button"
    android:layout_marginTop="60dp"
    android:layout_below="@+id/editText3"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Root #2"
    android:id="@+id/button2"
    android:layout_marginTop="69dp"
    android:layout_alignTop="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:id="@+id/textView2"
    android:layout_alignBottom="@+id/button"
    android:layout_alignTop="@+id/button"
    android:layout_alignRight="@+id/textView"
    android:layout_alignEnd="@+id/textView"
    android:layout_toRightOf="@+id/button"
    android:layout_toEndOf="@+id/button"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="false" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:id="@+id/textView3"
    android:layout_alignBottom="@+id/button2"
    android:layout_toRightOf="@+id/button2"
    android:layout_alignTop="@+id/button2"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned"
    android:ems="10"
    android:id="@+id/editText"
    android:layout_marginTop="32dp"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/textView2"
    android:layout_toStartOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned"
    android:ems="10"
    android:id="@+id/editText2"
    android:layout_below="@+id/editText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/textView2"
    android:layout_toStartOf="@+id/textView2" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number|numberSigned"
    android:ems="10"
    android:id="@+id/editText3"
    android:layout_below="@+id/editText2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/textView2"
    android:layout_toStartOf="@+id/textView2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="x^2"
    android:id="@+id/textView4"
    android:layout_alignTop="@+id/editText"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignStart="@+id/textView2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="x"
    android:id="@+id/textView5"
    android:layout_below="@+id/editText"
    android:layout_alignLeft="@+id/textView4"
    android:layout_alignStart="@+id/textView4" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="=0"
    android:id="@+id/textView6"
    android:layout_alignBottom="@+id/editText3"
    android:layout_alignLeft="@+id/textView5"
    android:layout_alignStart="@+id/textView5" />
</RelativeLayout>

person Giannis B    schedule 22.02.2016    source источник
comment
Пожалуйста, добавьте языковой тег к этому вопросу.   -  person Wai Ha Lee    schedule 22.02.2016


Ответы (2)


Вы сравниваете двойные значения с ==. Проблема в том, что он, скорее всего, не будет равен 0 из-за незначительной ошибки при сохранении двойных значений. Например, это будет что-то вроде 0,000000001 или -0,00000001. Вместо этого сравните так:

 if (Math.abs(a) < 0.0000001) { ... }

Также вы забыли разделить свои корни на 2 * a.

person Daniel Zolnai    schedule 24.02.2016

Итак, основная проблема, которую я вижу, заключается в том, что вы назначаете свои значения для a, b и c в методе onCreate вашего класса активности.

Это означает, что как только ваша активность создана, то есть до того, как пользователь успел ввести какие-либо данные в ваши поля EditText, вы пытаетесь прочитать указанный несуществующий ввод, то есть 0.

Вот почему в каждом методе onClick первое предложение if(), проверяющее нулевые значения, возвращает true. Потому что значения равны нулю.

Что вам нужно сделать, так это переместить эту часть каждой переменной:

    if (!c_temp.getText().toString().equals("")) {
        c = Double.parseDouble(c_temp.getText().toString());
    }else {
        c = Double.valueOf(0);
    }

в ваши OnClickListener классы, то есть в onClick методы, чтобы «обновить» значения, которые вы используете в своих вычислениях, на основе текущего пользовательского ввода.

person damian    schedule 24.02.2016