Lucas Pereira Lucas Pereira - 5 months ago 12
Java Question

How to show text instead numbers as a result of a math formula in Android App?

How are you? I need help with my first Android App.

I want to calculate the result of the gasoline price divided by the etanol price. I've already done that, with the result being displayed in the app.

But now I want to make it better. Instead of a number, I want the text field to display "Gasoline", if the result of gasoline / etanol is equal or greater than 0.7, and "Etanol", if the result is lower than 0.7.

How can I do that? I'm adding the code I already have. Thanks!




package br.com.espacoporto.espacoporto;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Inicio extends AppCompatActivity {

TextView totalTextView;
EditText gasolineTxt;
EditText etanolTxt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

totalTextView = (TextView) findViewById(R.id.totalTextView);
gasolineTxt = (EditText) findViewById(R.id.gasolineTxt);
etanolTxt = (EditText) findViewById(R.id.etanolTxt);

Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
float gasoline = Float.parseFloat(gasolineTxt.getText().toString());
float etanol = Float.parseFloat(etanolTxt.getText().toString());
float total = etanol / gasoline;
totalTextView.setText(Float.toString(total));
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_inicio, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

Answer

Should just be a simple if statement, yeah?

Also, your question said gasoline / etanol, so I used that instead of what you had in the code.

float total = gasoline / etanol;
if (total < 0.7)
    totalTextView.setText("Ethanol");
else 
    totalTextView.setText("Gasoline");

Or you can one-line that

totalTextView.setText( (gasoline / etanol) < 0.7 ? "Ethanol" : "Gasoline");