Format Doubles to String [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to nicely format floating types to String?
How can I list the number with up to two decimal places? I tried this method: http://developer.android.com/reference/java/text/NumberFormat.html but no luck. Below code. Maybe someone can help me.
package karcio.fuel.economy;
public class FuelEconomy extends Activity
{
private EditText editText1;
private EditText editText2;
private TextView textView4;
private TextView textView6;
private Button button1;
private double miles;
private double liters;
private double result;
private double convertMilesToKm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initParams();
}
private void initParams()
{
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView4 = (TextView)findViewById(R.id.textView4);
textView6 = (TextView)findViewById(R.id.textView6);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
calculate();
}
});
}
private void calculate()
{
miles = Double.parseDouble(editText1.getText().toString());
liters = Double.parseDouble(editText2.getText().toString());
convertMilesToKm = miles * 1.61;
result = 100 * liters / convertMilesToKm;
textView6.setText(Double.toString(convertMilesToKm));
textView4.setText(Double.toString(result));
}
}

You can do something like this:
String str = String.format("%.2f", 3.99999);
textView.setText(str);

Well you can try to manually do it.
//This is just an example
double number = result; //result is YOUR variable (ex. result = 23.1231231241920312)
int tmp = number * 100; //2312.31231241920312
number = (double)tmp / 100; //23.12
Hope this helps.
Note: You can skip the step where i declare an INT if you do it on the other line.
Update: The advantage of using this method is that you do not need to create an Object which is faster, but of course there are many ways.

Related

How do I take a number input, change it, then out put it, with submit button?

I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}

Unable to sync up answers the questions on an Android Multiplication app

I have a problem with my simple android app. When I launch it, the questions seems to be a step ahead of the answers I enter as input. For example If the question was to be 3x3 = ?, It will only accept the correct answer for the next question. So any answer I give in the current question will always be wrong. I tested this by continuously entering the same same answer.
Any pointers would be much appreciated. I hope this make sense!
public class MainActivity extends AppCompatActivity {
int value3;
int answer;
EditText answer_field;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView leftNumber = findViewById(R.id.left_number);
final ImageView rightNumber = findViewById(R.id.right_number);
Button myButton = findViewById(R.id.answer_button);
final int[] numberArray = new int[]{
R.drawable.number_0,
R.drawable.number1,
R.drawable.number2,
R.drawable.number3,
R.drawable.number4,
R.drawable.number5,
R.drawable.number6,
R.drawable.number7,
R.drawable.number8,
R.drawable.number9,
};
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
}
public void showToast(String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
}
Thank you!
You are generating the values at the onClick of your answer button wich means that the values to multiply will be set (or reset) randomly every time the user hit the answer button; put the logic to generate the values outside the onclick, so when the user clicks on it only the comparison will be made, somewhat like this:
[...]
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
[...]

Main activity not assigning values to variables

In my homework problem I am supposed to calculate a monthly loan payment based on the loan amount interest rate and length of the loan given by the user. This is to be done using intent.
When I run the application, the values of the variable never change from 0 and then it goes to the second page of the app where the results are supposed to be displayed but it says NaN where the result is supposed to be displayed.
I am very new to Android development and I have no clue where the problem is occurring so I posted all of the main Java code I have.
class named Loan.java
package com.example.collegeloanpayoffcalculator;
public class Loan
{
public static double loanAmount = 0.0;
public static double interestRate = 0.0;
public static int loanDuration = 0;
//public static double monthlyPayment = 0.0;
public double amount;
public double interest;
public double duration;
//public double payment;
public Loan() {}
public Loan(double amount, double interest, double duration)
{
this.amount = amount;
this.interest = interest;
this.duration = duration;
}
}
class named MainActivity.java
public void calculatePayment(View view)
{
Intent intent = new Intent(this, paymentViewActivity.class);
EditText loanAmount = (EditText) findViewById(R.id.loanAmount);
Editable amount = loanAmount.getText();
intent.putExtra("Loan.loanAmount", Double.valueOf(amount.toString()));
EditText interestRate = (EditText) findViewById(R.id.interestRateEditText);
Editable interest = interestRate.getText();
intent.putExtra(String.valueOf(Loan.interestRate), interest);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.duration);
int selected_id = radioGroup.getCheckedRadioButtonId();
RadioButton radio_b = (RadioButton) findViewById(selected_id);
intent.putExtra(String.valueOf(Loan.loanDuration), radio_b.getText().toString());
startActivity(intent);
}
}
class named paymentViewActivity.java
public class paymentViewActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loan_payment);
Intent intent = getIntent();
double amount = intent.getDoubleExtra("loanAmount", loanAmount);
double interest = intent.getDoubleExtra("interestRate", interestRate);
int duration = intent.getIntExtra("loanDuration", loanDuration);
double payment = amount * interest / (1 - 1 / Math.pow(1 + interest, duration * 12));
TextView Payment = findViewById(R.id.loanPayment);
Payment.setText(Double.toString(payment));
}
It is because you have different key when adding extended data to the intent. You're using the following in "Loan.loanAmount" key in calculatePayment method:
intent.putExtra("Loan.loanAmount", Double.valueOf(amount.toString()));
But you expect "loanAmount" in paymentViewActivity class:
public class paymentViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
double amount = intent.getDoubleExtra("loanAmount", loanAmount);
}
please take a note that Intent.putExtra(String, Value) is using a key-value format for the parameter. A string is a key identifier for a specific value.
So, use the same key for your putExtra. The safer way is using a constant String as a key in your related Activity. For example, use LOAN_AMOUNT_KEY constant string for your loan amount value:
public class paymentViewActivity extends AppCompatActivity {
public static final String LOAN_AMOUNT_KEY = "loanAmountKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// use the key to find the value
// you won't use the incorrect key because
// the key is tightly coupled to the activity
double amount = intent.getDoubleExtra(LOAN_AMOUNT_KEY, loanAmount);
}
}
then, in your calculatePayment method, use the key when saving the value:
public void calculatePayment(View view) {
Intent intent = new Intent(this, paymentViewActivity.class);
...
double amount = Double.valueOf(amount.toString());
intent.putExtra(paymentViewActivity.LOAN_AMOUNT_KEY, amount);
...
}
Note:
Use a correct java naming convention class name for your activity. For example, use PaymentViewActivity instead paymentViewActivity
Avoid using public static for your model member class. You're better use getter/setter.
intent.putExtra(String.valueOf(Loan.interestRate), interest); --> wrong
intent.putExtra(String.valueOf(Loan.loanDuration), radio_b.getText().toString());
You need to add String name only then you will get it from extras.
intent.putExtra("interest", interest);
intent.putExtra("loanduration", radio_b.getText().toString());

Compare the result of two TextViews Java/Android

I'm making a simple very simple android math game. But I cant manage to compare two TextViews to let the user know if they calculated correct or not???
Im not comparing them correctly as my if/else statement is only giving me the else output??
public class PlayActivity extends AppCompatActivity {
EditText number1;
EditText number2;
TextView result;
Button addNumbers;
TextView equalW;
TextView equalL;
TextView generate;
double num1,num2,sum;
Random r = new Random();
public View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
generate = (TextView)findViewById(R.id.textViewGenerate);
int generated = r.nextInt(101);
generate.setText(Integer.toString(generated));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
number1 = (EditText)findViewById(R.id.editTextNumber1);
number2 = (EditText)findViewById(R.id.editTextNumber2);
result = (TextView)findViewById(R.id.textViewSum);
addNumbers = (Button)findViewById(R.id.buttonAdd);
equalL = (TextView)findViewById(R.id.textViewLose);
equalW = (TextView)findViewById(R.id.textViewWin);
Button buttonGenerate = (Button)findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(listener);
addNumbers.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
sum = num1 + num2;
result.setText(Double.toString(sum));
if (generate.getText().toString().equals(result))
{
equalW.setText("Answer is correct");
}
else {
equalL.setText("lose");
}
}
});
}
You have one obvious problem and another lurking problem.
The obvious one: You have to compare a String with a String and not with a TextView. Hence replace if (generate.getText().toString().equals(result)) with if (generate.getText().toString().equals(result.getText().toString())).
The lurking one: If you see closely, sum is set as String in result and generated is set as String in generate. sum is of data type double and generate is of data type int. Comparing both will cause problem. This is like comparing "10".equals("10.0"). This is error prone. You need to set both these fields to a common data type.
Change if condition as:
if (generate.getText().toString().equals(result.getText().toString()))
{
}
Because result is view so call getText method for comparing String values.
result is textview so you have to write
if (generate.getText().toString().equals(result.getText().toString))

My Simple Interest calculator is crashing with a null pointer exception error

My Simple Interest calculator is crashing with a null pointer exception error, not sure what the problem is, there are no errors in the IDE before I complile, this is new to me. Here is my code and logcat: edit: Icouldn't post a logcat as the editor thinks it's code and I can't get it to format correctly
Code:
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity
implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private int years;
private TextView YT;
private SeekBar bar;
private EditText principal = (EditText) findViewById(R.id.PA_field);
private EditText interest = (EditText) findViewById(R.id.IR_field);
public EditText pvalue;
public EditText ivalue;
private double mPvalue = 0;
private double mIvalue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
bar = (SeekBar)findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
pvalue = (EditText) principal.getText();
ivalue = (EditText) interest.getText();
String s = principal.getText().toString();
mPvalue = Double.parseDouble(s);
String s2 = interest.getText().toString();
mIvalue = Double.parseDouble(s2);
}
#Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
#Override
public void onStartTrackingTouch (SeekBar seekBar){
}
#Override
public void onStopTrackingTouch (SeekBar seekBar){
}
#Override
public void onClick(View view) {
TextView fTextView = (TextView) findViewById(R.id.finalText);
double finValue = mPvalue * (mIvalue/100) * years;
fTextView.setText("The interest for " + pvalue + "at a rate of " + ivalue + "for " + years + "year(s) is " + finValue);
}
}
You can't instantiate view variables by calling findViewById as you're declaring them. You have to declare them first and then instantiate either in onCreate or some method invoked after the Activity is bound with the view. Make sure to do it after setContentView(R.layout.sicalculator);
Okay, after seeing your layout, stacktrace and reading more in to your code, I saw that there are fundamental issues which ought to give you more crashes, so let's fix them.
First, pvalue and ivalue variables are unnecessary! Remove them.
Related: You cannot assign an Editable to an EditText. So this line is invalid ivalue = (EditText) interest.getText(); Because getText() returns an Editable. But these are all redundant and unnecessary anyways.
Second, in onCreate method, let's just initialize views and not try to get values and parse them yet; the user (or you) haven't interacted nor entered any values there yet; so trying to parse null values in to Doubles will crash your app.
Your onCreate method should look something like this. (Note that I'm also initializing your button and setting the click listener here).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
principal = (EditText) findViewById(R.id.PA_field);
interest = (EditText) findViewById(R.id.IR_field);
bar = (SeekBar) findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
calcBtn = (Button)findViewById(R.id.calc_btn);
calcBtn.setOnClickListener(this);
}
Now, you should get the values and parse them in your onClick listener - only when the user has entered values and clicked on the Calculate button, so your onClick() method should look something like this:
#Override
public void onClick(View view)
{
TextView fTextView = (TextView) findViewById(R.id.finalText);
mPvalue = Double.valueOf(principal.getText().toString());
mIvalue = Double.valueOf(interest.getText().toString());
double finValue = mPvalue * (mIvalue / 100) * years;
fTextView.setText("The interest for " + mPvalue + "at a rate of " + mIvalue + "for " + years + "year(s) is " + finValue);
}
And that should clear the logic and order or declaring, initializing, retrieving values from variables for you. I hope this explains how Java and Android basics work.
Oh by the way, I actually ran the code and it's running on my phone so this isn't just off the top of my head. If this helped you, please accept the answer.
Best wishes,

Categories

Resources