Result: NaN will not work? - java

Within the app I have different activity pages that call for the user to enter numerical data. I think of storing the data as below so I can use it on the final activity:
public void onClick(View v) {
String variable1 = input.getText().toString();
Double.parseDouble(variable1); //stores information put into variable
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("variable1",variable1);
startActivity(myintent);
I do this same process for all the other activities up to the final one where I have:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);{
setContentView(R.layout.activity_iie);
Bundle extras = getIntent().getExtras(); //retrieves variables stored for formula
if(extras !=null){
double variable1 = extras.getDouble("VARIABLE1");
double vari2 = extras.getDouble("VARI2");
double vari3 = extras.getDouble("VARI3");
double finalvari = extras.getDouble("finalvari");
double solution= ((((vari2 - vari1) / (vari3) + finalvari)));
String lastString = "Result:" + solution; //prints out
TextView lastText = (TextView) findViewById(R.id.solution1);
lastText.setText(lastString);
}
I don't have any errors, but when I get to this final activity it prints out "Result:NaN". I'm trying to figure out why it is printing NaN; everything is set as a double.
What could cause this?
Update
#Melquiades
Yes I replaced the strings with the doubles as shown below:
'c.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
double variable1 = Double.parseDouble(input.getText().toString()); //stores information put into variable
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("variabele1",variabele1);
startActivity(myintent);
'
Then in my final activity that is suppose to print the answer:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);{
setContentView(R.layout.activity_iie);
Bundle extras = getIntent().getExtras(); //retrieves variables stored formula
if (extras != null){
double variable1 = extras.getDouble("variable1");
double vari2 = extras.getDouble("vari2");
double vari3 = extras.getDouble("vari3");
double engagement = extras.getDouble("engagement1");
double solution= ((((vari2-variable1)/(vari3))+finalvari));
String lastString = "Result:" +solution; //prints out
TextView lastText= (TextView) findViewById(R.id.solution1);
lastText.setText(lastString);
Decided to post some more to potentially help like you suggested.

In the launching end, you just set one extra variable1.
In the receiving end, you attempt to four values from extras:
double variable1 = extras.getDouble("VARIABLE1");
double vari2 = extras.getDouble("VARI2");
double vari3 = extras.getDouble("VARI3");
double finalvari = extras.getDouble("finalvari");
getDouble() will return 0.0 if the key is not present.
Now, in here
double solution= ((((vari2-vari1)/(vari3)+finalvari)));
you divide by zero, which in floating point math causes the result to be Not a Number (NaN).

Key issue is that put String into intent:
String variable1 = input.getText().toString();
Double.parseDouble(variable1); //stores information put into variable
//...
myintent.putExtra("variable1",variable1); <- variable1 is a string,
and when you extract it later with getDouble() you will get, quote :
0.0 if no mapping of the desired type exists for the given key
So you should put double in your intent instead :
double variable1 = Double.parseDouble(input.getText().toString());
myintent.putExtra("variable1",variable1);
Please note, it is very important to use identical key String for mapping, when you extract your double, i.e. use "variable1", case-sensitive :
double extractedVar1 = extras.getDouble("variable1");
You could use extras.containsKey() to verify that your mapping exists.

All the advices are correct. but you are doing one cardinal mistake...
When you're sending your variables, you do:
myIntent.putExtra("variable1", variable1);
Then when your receive, you do:
double variable1 = extras.getDouble("VARIABLE1");
Your keys are NOT THE SAME. 'variable1' and 'VARIABLE1' are not equal, hence instead of the value of variable 1, you are probably getting 0 instead, and all your calculations are wrong.
For this reason, it's a good practice to use static finals for keys. Declare in your first activity:
public static final String KEY_VARIABLE1 = "variable1";
Use it when inserting in an intent:
myIntent.putExtra(KEY_VARIABLE1, variable1);
And when retrieving:
double variable = extras.getDouble(ActivityWhereThisKeyIsDeclared.KEY_VARIABLE1);
Do it for all your variables.

Related

How to change Text view to int and use it in mathematical operations?

Hello I'm trying to make an app that gives you 2 random numbers and the user has to add the 2 random numbers, so my error is that that the random numbers are widgets not integers,
I have tried hundreds of explinations but nothing is working.
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
if (num1 + num2){
}
}
and this is the error:
bad operand types for binary operator '+' first type: TextView second
type: TextView
The problem you have is well described by the error you are receiving.
From the code snippet you have provided, I am guessing num1 and num2 are references to textview objects.
You CANNOT perform addition on the textview objects themselves, but rather on their content.
So, what you are trying to achieve is this:
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
String num1String = num1.getText().toString();
String num2String = num2.getText().toString();
int firstNumber = Integer.parseInt(num1String);
int secondNumber = Integer.parseInt(num2String);
if (firstNumber + secondNumber){
// YOUR LOGIC
}
}
Or better yet, you could save the generated random numbers to variables and use them later, like so:
public void action(View v){
int randomNumberOne = randNum1.nextInt(10);
int randomNumberTwo = randNum2.nextInt(10);
num1.setText(String.valueOf(randomNumberOne));
num2.setText(String.valueOf(randomNumberTwo));
userAnswer.getText();
if (randomNumberOne + randomNumberTwo){
// YOUR LOGIC
}
}
You can follow the below steps. i assume randNum1 and randNum2 is random number and num1 and num2 is TextView.
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
int randNumber1 = Integer.parseInt(num1.getText().toString());
int randNumber2 = Integer.parseInt(num2.getText().toString());
if (randNumber1 + randNumber2 ){
//your logic write here
}else{}
}

Returning nothing instead of NaN

I'm creating a simple app that calculates BMI and I'm struggling with one small problem. I have 2 edit text fields, which are allowed to type numbers only. The point is when one of the text fields are empty the app is to generate a toast message and display nothing. I wrote an if statement to check if an edit text is empty and if not just to calculate further.
All would work fine, but I needed to put return statement and Android Studio suggested me writing "return 0;" so did I.
This is the code responsible for calculations:
/// parse input value from edittext field into double type
private double weight() {
EditText weightInput = (EditText) findViewById(R.id.weight_input);
String sWeightInput = weightInput.getEditableText().toString();
if (sWeightInput.matches("")){
Toast.makeText(this, R.string.noweight, Toast.LENGTH_SHORT).show();
} else {
String weight = sWeightInput;
double weightTyped = Double.parseDouble(weight);
return weightTyped;
}
return 0;
}
private double heigh() {
EditText heightInput = (EditText) findViewById(R.id.height_input);
String sHightInput = heightInput.getEditableText().toString();
if (sHightInput.matches("")){
Toast.makeText(this, R.string.noheight, Toast.LENGTH_SHORT).show();
} else {
String height = sHightInput;
double heightTyped = Double.parseDouble(height);
heightTyped = heightTyped / 100;
heightTyped = heightTyped * heightTyped;
return heightTyped;
}
return 0;
}
//make calculations and return the output value
public void makeCalculations(View view){
double result = weight() / heigh();
String message = String.valueOf(result);
TextView bmiSummaryTextView = (TextView) findViewById(R.id.bmi_calculation);
bmiSummaryTextView.setText(message);
}
This is the interface of the app.
To sum up, all I want to do is to display nothing instead of NaN (not a number).
Return a non-primitive Double rather than a double, and you will be able to use null as a value. Be sure to check for this value though, or you'll run into a NullPointerException.
Alternatively, you could look into using optionals, but since you're using Android you might need an external library for that (unless your minimum SDK version is high enough, then you can use Java 8's Optional).
The problem is probably if in your calculation weight() / height height is 0 it outputs NaN because it is infinity.
Also put your return 0; after Toast.makeText() in the condition. AS grumbles because you are not returning a value in the if branch.
if (sHightInput.matches("")){
Toast.makeText(this, R.string.noheight, Toast.LENGTH_SHORT).show();
return 0;
}
Maybe this will help you also to avoid dividing by zero.
public void makeCalculations(View view) {
String message = "Invalid input!";
if (weight() > 0 && height() > 0) {
double result = weight() / heigh();
String message = String.valueOf(result);
}
TextView bmiSummaryTextView = (TextView) findViewById(R.id.bmi_calculation);
bmiSummaryTextView.setText(message);
}

Convert number in textview to int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this

The number of parameters depends on the previous activity

I'm trying to get the parameters that are provided by the previous activities. The number of parameters is not fixed and my method should be able to read all of them (from 1 to n). The number of the parameters is given by the parameter n_inputs. I've tried to do it with the following code, which is correct by the compiler, but it has some problem and I don't know where...I think it must be something related with the array param[ ]. Could you help me, please??
double params[];
int n_inputs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//I'm gonna get the parameters from the previous activity
Bundle b = getIntent().getExtras();
//here I get the number of inputs from the previous activity
n_inputs = b.getInt("ninputs");
// I create a new array with dimension "i_inputs"
params= new double[n_inputs];
if(n_inputs>0)
{
for (int i=0;i<n_inputs;i++)
{
params[i] = b.getDouble("param"+(i+1));
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
//Now I try to show the parameters in a toast
Context context = getApplicationContext();
CharSequence text = "parameter 1 "+params[0] +" param 2 "+ params[1] ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Thank you very much!!
You could use Bundle.putDoubleArray() and Bundle.getDoubleArray() will be simpler anyway.

textView wont display decimals

I am having an issue with my program, my textveiw will not display any decimals, heres the break down on whats happeneing. The user enters a number in a textEdit (Also how do i make the textedit only accept numbers AND a decimal point?) that number gets converted to a int, sent to my second activity, diveded by 3600, then displayed in a textveiw box. The issue is that when that number is displayed it has no decimal value, for example if its less than 1 it will not display anything, how can i go about fixing this? i need it to at least go to the 1000th place.
Here is my code one activity1:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// Gather text from text boxes
EditText editText = (EditText) findViewById(R.id.hourly_wage);
//Create String from text
String message1 = editText.getText().toString();
//Convert String to Int
int HW = 0;
try{
HW = Integer.valueOf(message1);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
// Send Integers to PayTracker.java
intent.putExtra(MESSAGE_HW, HW);
// start new activity
startActivity(intent);
And then this is activity2 where the number needs to be displayed:
public void sendMessage(View view) {
// Receive messages from options page
Intent intent = getIntent();
int HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
// Calculate pay per second
int PPS = 0;
PPS = (HW/3600);
// set textView
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(PPS));
}
Any help would be appreciated! thanks!
Use doubles or floats. From what I see, everything should work except that you forgot that 5 divided by 2 as int is 2, and not 2.5.
so do as gtumca said and use doubles; longs are just bigger ints.
in other words...
activity1
try{
HW = Double.valueOf(message1);
}
activity 2
//double HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
double HW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
// pay is rarely a round number
double PPS = HW / 3600;
that number gets converted to a int
Integers dont have decimals :)
As to the EditText only accepting numbers:
EditText, inputType values (xml)
Set one of those types to your EditText in the Layout xml like:
android:inputType="number"
You are using int as data type so you are getting int values only
double PPS = 0;
^^^^^^
instead of
int PPS = 0;
You shouldn't use float or double to keep numbers with such big precision. Float and double cannot represent decimal fractions exactly due to their internal representations. Please, check BigDecimal if you want 1000-digit precission(or more).

Categories