简体   繁体   中英

Android Studio Java: How to I store the value of an EditText Input as double?

so I am working on a small application which reads 5 different inputs (double type) from 5 different EditTexts. So each EditText field represents 1 input containing a double value.

A buttom named "calculate" then calculates the average by using (input1 + input2 + input3 + input4 + input5 / 5) and stores it into a TextView called "average".

My question is how do I access the input to use it in my calculation method?

This is what my code looks like so far:

package com.example.durchschnittrechnen;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

EditText et_zahl1, et_zahl2, et_zahl3, et_zahl4, et_zahl5;
TextView tv_ergebnis;
Button btn_berechnen, btn_reset;

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

public void setupUI() {
    et_zahl1 = findViewById(R.id.et_zahl1);
    et_zahl2 = findViewById(R.id.et_zahl2);
    et_zahl3 = findViewById(R.id.et_zahl3);
    et_zahl4 = findViewById(R.id.et_zahl4);
    et_zahl5 = findViewById(R.id.et_zahl5);
    btn_berechnen = findViewById(R.id.btn_berechnen);
    btn_reset = findViewById(R.id.btn_reset);
    tv_ergebnis = findViewById(R.id.tv_ergebnis);
}

public void reset() {
    btn_reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            et_zahl1.setText("");
            et_zahl2.setText("");
            et_zahl3.setText("");
            et_zahl4.setText("");
            et_zahl5.setText("");
            tv_ergebnis.setText("");
        }
    });
}

public void calculateAverage() {
    btn_berechnen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            
        }
    });
}

}

I have no idea how I proceed now. Any help is welcome. Thanks.

There is a getText() function. It provides whatever text is in the box. You then would have to convert it to a Double.

 String str = mEdit.getText().toString();
 double dnum = Double.parseDouble(str);

Edit Text value returns string, you can covert string to double. Here is an example:

double et_zahl1_dbl = new Double(et_zahl1.getText().toString());

I do recommend adding user messaging, if user enters anything else besides double.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM