2016-02-22 4 views
0

Я хотел создать простой квадратичный алгоритм решения, но когда я его запустил, он попадает в первый оператор 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> 
+0

Пожалуйста, добавьте тег на этот вопрос. –

ответ

0

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

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

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

0

Таким образом, главная проблема, которую я вижу, что вы назначаете свои значения 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 методы, чтобы «освежить» значения, которые вы используете в своих расчетах на основе тока пользовательский ввод.

+0

большое спасибо. работал как шарм –

Смежные вопросы