I have made an calculation, took of the decimals but now i would like to make so that it show a down rounded number.
I found that i can use math.floor but i can't get it in the code.
I took the decimals off but can't get it to round down.
code is like this (the part which does the math):
public void onClick(View view) {
if (etBarfles.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters per " +
"minuut in!", Toast.LENGTH_SHORT).show();
} else {
if (etInhoudfles.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters per " +
"minuut in!", Toast.LENGTH_SHORT).show();
} else {
if (etLitersperminuut.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters " +
"per minuut in!", Toast.LENGTH_SHORT).show();
} else {
}
tvResult.setText(nodecimals((((Float.parseFloat(etBarfles.getText().toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
}
}
}
private String nodecimals(float val) {
return String.format("%.0f", val);
}
Try the following
tvResult.setText(String.valueOf((int) Math.floor(((Float.parseFloat(etBarfles.getText()
.toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
(int) Math.floor() will convert the value to an integer floor value, and then String.valueOf() will convert that int to String, so that you can set the same to the TextView.
THINGS TO IMPROVE:
You can make your code better by following these guidelines:
You are using the same line etBarfles.getText().toString() in multiple places for your check conditions. Its best if you initialize a variable with that value. Something like
String etBarFilesText = etBarfles.getText().toString();
Your condition etBarfles.getText().toString().equals("") can be written the Android way as follows
!TextUtils.isEmpty(etBarFilesText)
Your strings should be defined in your strings.xml. So if your error msgd is named error_string in the strings.xml then your Toast message will look something like this.
Toast.makeText(getActivity(), getString(R.string.error_string), Toast.LENGTH_SHORT).show();
Your line
tvResult.setText(nodecimals((((Float.parseFloat(etBarfles.getText().toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
could have been wayy simpler, and more readable if you used different variables, instead of writing everything in a big single sentence.
Related
I want to display the value toast in text view
Code :
public void onAnimationEnd(Animation animation) {
#SuppressLint({"WrongConstant", "ShowToast"}) Toast toast = Toast.makeText(this, " " + String.valueOf((int)(((double)this.intNumber)
- Math.floor(((double)this.lngDegrees) / (360.0d / ((double)this.intNumber))))) + " ",0);
toast.setGravity(49,0,0);
this.blnButtonRotation = true;
b_start.setVisibility(View.VISIBLE);
}
i agree with Laura. It's hard to guess what you are asking for here.
If you want to show the Toast you should add .show() at the end of your toast and change the duration to Toast.LENGHT_SHORT or Toast.LENGTH_LONG instead of "0".
e.g:
Toast.makeText(this, "yourString", Toast.LENGTH_LONG).show()
If you want to access the the value of the String inside the Toast, there is currently no way to do something like that. So the only option is to store it in its own variable:
String numberAsString = String.valueOf((int(((double)this.intNumber) - Math.floor(((double)this.lngDegrees) / (360.0d / ((double)this.intNumber)))));
textView.setText(numberAsString);
//Toast toast = Toast.makeText(this, numberAsString, Toast.LENGHT_LONG).show();
I am making a unit converter, but if I do not enter any value into edit text and press the calculate button the app crashes with error Invalid float: "". Also, I want to forbid zeroes from being entered before numbers (eg. 0300). How do I accomplish this?
//handle calculate
calcButton=(Button)findViewById(R.id.calcButton);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Spinner spinner = (Spinner) findViewById(R.id.unit_spinner);
String spinnerText = spinner.getSelectedItem().toString();
EditText unit_edit = (EditText) findViewById(R.id.unit_edit);
amount = Float.valueOf(unit_edit.getText().toString());
if (unit_edit.getText().toString().equals(null)) {
Toast.makeText(getApplicationContext(), "Insert Value To Convert",
Toast.LENGTH_LONG).show();
} else {
switch (spinnerText) {
case "Kilograms":
kilograms = amount;
grams = amount * 1000;
ListView();
break;
case "Grams":
grams = amount;
kilograms = amount / 1000;
ListView();
break;
}
}
}
});
}
You are probably getting an NumberFormatException thrown since the EditText fields text is "" and "" is not a valid float value, the exception is thrown at the following line:
amount = Float.valueOf(unit_edit.getText().toString());
What you'll need to do is add some validation and checking before trying to get the float value of a String.
Check the methods documentation for more details http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)
This might be useful for your EditText to limit input to numbers only.
<EditText
android:id="#+id/unit_edit"
android:inputType="number"
/>
You can also limit the digits, type of number such as decimal
<EditText
android:id="#+id/unit_edit"
android:digits="0123456789."
android:inputType="numberDecimal"
/>
You can't parse an empty value to float. You should first test if it's empty, and then do what you want, something like this:
String text = unit_edit.getText().toString();
if(!text.isEmpty()){ // Test if the text is empty
if(text.matches("[0-9]+")){ // Test if it only contains numbers, using REGEX
amount = Float.valueOf(text); // Only then parse to float.
// Switch and rest of the stuff
} else {
Toast.makeText(getApplicationContext(), "Use only numbers from 0 to 9.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "The field is empty",
Toast.LENGTH_LONG).show();
}
The comments explain what's going on. About the leading 0 in some numbers, using "valueOf" will remove it already, and 0300 will be parsed as 300, so there's nothing to worry about.If you still want something related to it, let me know and i'll edit my answer.
Can someone help me, I'm killing myself over here. So in my activity I have this code and the application constantly displays that CurrentQ is not equal (currentQ.getODG() != answer.getText()) to the answer
I can see through LogCat with Log.d that the words are identical. I just can't understand what am I doing wrong.
08-25 05:28:45.125: D/yourans(25316): na život u mraku na život u mraku
this is from log cat
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getODG() + " " + answer.getText());
if (currentQ.getODG().equals(answer.getText())) {
answer.setBackgroundResource(R.drawable.radiotocan);
Toast poruka1 = Toast.makeText(getApplicationContext(), "Točno!",
Toast.LENGTH_LONG);
View vieew1 = poruka1.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew1.setBackgroundResource(R.drawable.toast1);
poruka1.setView(vieew1);
poruka1.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka1.show();
score1++;
Log.d("score1", "Your score" + score1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}
else if (currentQ.getODG() != answer.getText()) {
answer.setBackgroundResource(R.drawable.radionetocan);
Toast poruka2 = Toast.makeText(getApplicationContext(),
"Netočno, točan odgovor je:" + currentQ.getODG(),
Toast.LENGTH_LONG);
View vieew2 = poruka2.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew2.setBackgroundResource(R.drawable.toast);
poruka2.setView(vieew2);
poruka2.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka2.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}
Try
if(currentQ.getODG().equalsIgnoreCase(answer.getText()))
instead of
if(currentQ.getODG()!=answer.getText())
Hope it helps!
Java uses the double-equals sign to check to see if the objects the two variables point to are the same object, not whether they are equivalent. Since both Strings are each returned by two separate method calls, they will never be the same object.
Instead you'll want to use one of the equality-testing methods from the String class:
.equals(String b) Tests to see if the two strings are exactly the same.
.equalsIgnoreCase(String b) Tests to see if the two strings are the same, ignoring whether they're uppercase or lowercase.
There are more options you can find in the String class's documentation, just check the public methods list.
In your case, change this line:
else if (currentQ.getODG() != answer.getText()) {
To read like:
else if (!currentQ.getODG().equals(answer.getText())) {
But for more flexibility in recognizing answers, use .equalsIgnoreCase() like this:
else if (!currentQ.getODG().equalsIgnoreCase(answer.getText())) {
try this:
change:
currentQ.getODG().equals(answer.getText())
to:
currentQ.getODG().trim().equalsIgnoreCase(answer.getText().trim())
change:
else if (currentQ.getODG() != answer.getText())
to:
else
I think probably there's blank space in your string, so use trim() to cut them out, then compare the strings while ignoring capital letter.
FYI: Reference.
I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
im trying to compare a text in android to avoid refreshing texts if it's not necessary (otherwise the texts for different fields are refreshed every 50ms).
With normal texts it is not a problem. Everything works fine.
But: If there are numbers in text the text seems not to be equal. Why?
Some examples:
"Abschaltpunkt" is equal to "Abschaltpunkt" (OK) /
"Gewicht" is equal to "Gewicht" (OK) /
"100 kg" is NOT equal to "100 kg" (NOK) /
"Abschaltpunkt 2" is NOT equal to "Abschaltpunkt 2" (NOK"
A new question after edit (the comparsion works fine now).
As you see I use the UI thread for refreshing the text. This app works in a network and receives arround 300 messages per second with different data (yes, it is necessary). Therefore I need the comparsion otherwise the thread is blocked and the app won't respond on user inputs.
Is there another solution? Or is my solution a good one?
This is my code:
/**
* Compares the current and new text und updates the text if necessary
* #param RessourceID given by R.id...
* #param New text
*/
private void ChangeText (final int RessourceID, final String sText) {
try {
TextView tv = (TextView) findViewById(RessourceID);
// Erst prüfen ob Text ersetzt werden muss -> Spart Rechenzeit
if (tv.getText().toString().equals(sText)) {
Log.e(this.getClass().getSimpleName(), "Text nicht ersetzen: " + tv.getText() + " != " + sText);
} else {
ChangeTextThread(tv, sText);
Log.e(this.getClass().getSimpleName(), "Text ersetzen: " + tv.getText() + " != " + sText );
}
} catch (Throwable t) {
Log.e(this.getClass().getSimpleName(), "ChangeText", t);
}
}
/**
* Change the text in UI tread
*/
private void ChangeTextThread (final TextView tv, final String sText) {
this.runOnUiThread(new Runnable() {
public void run() {
try {
tv.setText(sText);
} catch (Throwable t) {
Log.e(this.getClass().getSimpleName(), "ChangeTextThread", t);
}
}
});
}
try this way
if(tv.getText().toString().equals(sText))
Used .equals() or .equalsIgnoreCase() method for string comparison
Try below code:
if(tv.getText().toString.equalsIgnoreCase(sText)){
//Do your stuff here
}