Процентный калькулятор не работает в Android Studio - PullRequest
1 голос
/ 22 мая 2019

Мое приложение содержит 3 свойства EditText

Первое свойство принимает значение процента от пользователя, а второе свойство должно получить число, для которого пользователь хочет рассчитать процент, а третье свойство должно отобразитьрезультат.

Я прикрепил код Java и XML ниже!Спасибо.

У меня логическая ошибка.Я ожидаю получить значение определенного числа с указанным процентом, введенным пользователем.

Например.Пользователь хочет 25% от 200, затем в первом EditText пользователь вводит 25%, а затем во втором Edittext он вводит 200, и значение должно автоматически отображаться в третьем Edittext, т.е. 50. Но здесь третий Edittext не обновляет свойзначение и отображение 0.0.

    <EditText
    android:id="@+id/txtbx1"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.462" />

    <EditText
    android:id="@+id/txtbx2"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.585" />

    <EditText
    android:id="@+id/txtbx3"
    android:layout_width="179dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="number"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.708" />

    <TextView
    android:id="@+id/txtvw1"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="%"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.144"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.462" />

    <TextView
    android:id="@+id/txtvw3"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="is"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.144"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.708" />

    <TextView
    android:id="@+id/txtvw2"
    android:layout_width="33dp"
    android:layout_height="45dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="of"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.133"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.585" />

    <TextView
    android:id="@+id/PC"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:fontFamily="@font/sansationbold"
    android:text="Percentage Calculator"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.139" />

    <TextView
    android:id="@+id/acl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="320dp"
    android:layout_marginLeft="320dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:fontFamily="@font/casanova"
    android:text="Arcis Computer Labs"
    android:textSize="10dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.988" />

    setContentView(R.layout.activity_mainscreen);
    EditText txtbx1 = (EditText)findViewById(R.id.txtbx1);
    EditText txtbx2 = (EditText)findViewById(R.id.txtbx2);
    EditText txtbx3 = (EditText)findViewById(R.id.txtbx3);
    TextView txtvw1 = (TextView)findViewById(R.id.txtvw1);
    TextView txtvw2 = (TextView)findViewById(R.id.txtvw2);
    TextView txtvw3 = (TextView)findViewById(R.id.txtvw3);

    float txt;
    try{
        txt = Float.parseFloat(txtbx1.getText().toString());
    }
    catch(NumberFormatException x){
        txt = (float) 0.0;
    }
    float txt2;
    try{
        txt2 = Float.parseFloat(txtbx2.getText().toString());
    }
    catch(NumberFormatException ex){
        txt2 = (float) 0.0;
    }
    Percent = (txt2 * txt) / 100;
    txtbx3.setText(String.valueOf(Percent));
}

Ответы [ 4 ]

0 голосов
/ 22 мая 2019

В вашем коде текст EditText не будет обновляться, поскольку метод onCreate будет вызываться только при запуске приложения. Поэтому необходимо добавить прослушиватель изменений на EditText. Попробуйте следующий код:

float txt1 = 0, txt2 = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText txtbx1 = (EditText) findViewById(R.id.txtbx1);
    EditText txtbx2 = (EditText) findViewById(R.id.txtbx2);
    final EditText txtbx3 = (EditText) findViewById(R.id.txtbx3);
    TextView txtvw1 = (TextView) findViewById(R.id.txtvw1);
    TextView txtvw2 = (TextView) findViewById(R.id.txtvw2);
    TextView txtvw3 = (TextView) findViewById(R.id.txtvw3);


    txtbx1.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() != 0)
                txt1 = Float.parseFloat(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            changeValue(txt1, txt2, txtbx3);
        }
    });

    txtbx2.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() != 0)
                txt2 = Float.parseFloat(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            changeValue(txt1, txt2, txtbx3);
        }
    });


}

private void changeValue(float txt1, float txt2, EditText txtbx3) {
    float Percent = (txt2 * txt1) / 100;
    txtbx3.setText(String.valueOf(Percent));
}
0 голосов
/ 22 мая 2019

Если Percent - это определенное вами число с плавающей запятой, следующее должно это исправить:

Percent = (txt2 * txt) / 100f;
0 голосов
/ 22 мая 2019

Сначала необходимо убедиться, что первый и второй EditText заполнены, а затем изменить значение третьего EditText.
см. https://developer.android.com/reference/android/text/TextWatcher
Для этого необходимо добавить TextWatcher как в первый, так и во второй EditText;давайте назовем их edtPercentage, edtOriginalValue и edtFinalValue:

edtPercentage.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    //Here you can define code to happen before the change
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after{
    //Here you can define code to happen on change
    }

    @Override
    public void afterTextChanged(Editable s) {
    //Here you can define code to happen after the change

    if(edtPercentage.getText().length()>0 && edtOriginalValue.getText().length()>0)
    //edtFinalValue.setText([metod to do the calculation and parse to string]);
    }
});


сделать то же самое для EditText edtOriginalValue, поэтому, когда вы изменяете либо процент, либо значение для получения процента, будет обновляться окончательный EditText

0 голосов
/ 22 мая 2019

Предполагая, что Percent определен как число с плавающей запятой, вы должны заменить вторую на последнюю инструкцию следующую команду:

Percent = (txt2 * txt) / 100.00;

Если вы используете в уравнении буквенное число, являющееся целым числом, например 100,который также включает в себя числа с плавающей запятой, тогда результат может быть представлен как целое число, и может произойти округление или усечение.

Я думаю, что ваша проблема вызвана тем, что пользователь вводит «25%» в текстовое поле 1. Когда вы пытаетесьчтобы разобрать это в число с плавающей точкой, вы получите ошибку формата, потому что «%» не является числовым значением.Вам нужно каким-то образом преобразовать 25% в .25, прежде чем пытаться разобрать это значение в число с плавающей точкой.В противном случае он сгенерирует ошибку и заменит первое значение как 0.0, что приведет к тому, что вычисление процентов приведет к 0.0

float txt;
try{
    txt = Float.parseFloat(txtbx1.getText().toString()); // this will generate an error on a value of '25%'
}
catch(NumberFormatException x){
    txt = (float) 0.0; // so, this will execute.
}

. Это можно проверить, поставив точку останова в своем коде в этой строке вИсключение и доказательство того, что на самом деле здесь происходит исключение.

...