Hi Im trying to learn Java for android and I can't get the simplest code to work.
I'm trying to write a percent calc. The code should work, but it wont let me convert float to string.
totalTextView = (TextView) findViewById(R.id.totalTextView);
percentageTxt = (EditText) findViewById(R.id.percentagetxt);
numberTxt = (EditText) findViewById(R.id.numbertext) ;
Button calcbutton = (Button) findViewById(R.id.calcbutton);
calcbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
float percentage = Float.parseFloat(percentageTxt.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberTxt.getText().toString());
totalTextView.setText(Float.toString(total));
}
});
}
When i try to do it seperatly with an extra variable there are no errors, but the program still tells me 10 % of 100 is 1 XD.
totalTextView = (TextView) findViewById(R.id.totalTextView);
percentageTxt = (EditText) findViewById(R.id.percentagetxt);
numberTxt = (EditText) findViewById(R.id.numbertext) ;
Button calcbutton = (Button) findViewById(R.id.calcbutton);
calcbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
float percentage = Float.parseFloat(percentageTxt.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberTxt.getText().toString());
final String s = Float.toString(total);
totalTextView.setText(s);
}
});
}
also i'm having trouble formatting the elements. drag and drop doesn't work. They all just get stacked. If I enter translation value individualy, i can't see half the elements in my content main.
!http://imgur.com/TJBIUsf
I know this is beginner stuff, that's probably why I cant find any other posts on this, ;) but i just can't figure it out.
Try String.valueOf(floarValue) instead of Float.toString(floatValue)
Related
I'm writing a simple Percentage Calculator android app in Android Studio. Here's my psuedo:
resultView = (TextView) findViewById(R.id.ResultView);
percentageText = (EditText) findViewById(R.id.PercentageInput);
numberText = (EditText) findViewById(R.id.NumberInput);
Button calcButton = (Button) findViewById(R.id.Calculate_btn);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(percentageText.length() != 0 && numberText.length() != 0)
{
float percentage = Float.parseFloat(percentageText.getText().toString()) / 100;
float result = percentage * Float.parseFloat(numberText.getText().toString());
resultView.setText(Float.toString(result));
}
else if(percentageText.length() == 0 && numberText.length() == 0)
{
resultView.setText("Don't be dumb...");
}
}
});
so it seemed like everything was working fine. Simple percentages are always right. 50%100=50, 25%50=12.5 ... but then I get to 3 and 6. 3%10= 0.29999998 ... shouldn't it be .3? and 60%100= 60.000004 ... Any help out there?
It has to do with the fact that double variables have a limited number of bits. This is like saying 1/3 = 0.33333333 when really is should be equal to 0.33333333... forever!
Read about Floating points and Double precision
I'm working on a multiple choice quiz application, and what I'm trying to accomplish is having my "Next Question" button get values from an array in which my questions/answers are stored. The code I have so far loops through the first question, [0][0] etc. as well as the second question stored at [1][0] etc. I have 10 questions stored in my array, and I'm trying to loop through all of them. What should I change in this code to make that happen?
public void addListenerOnButton(){
Button nextQButton = (Button) findViewById(R.id.nextQButton);
nextQButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < qAndA.length; i++) {
TextView questionText = (TextView) findViewById(R.id.questionText);
questionText.setText(qAndA[i][0]);
RadioButton radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
radioButton1.setText(qAndA[i][1]);
RadioButton radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
radioButton2.setText(qAndA[i][2]);
RadioButton radioButton3 = (RadioButton) findViewById(R.id.radioButton3);
radioButton3.setText(qAndA[i][3]);
RadioButton radioButton4 = (RadioButton) findViewById(R.id.radioButton4);
radioButton4.setText(qAndA[i][4]);
}
}
});
}
I see no need for a for loop here. Why not just have a counter which increments every time the button is clicked?
int count = 0;
Your onClick method could look something like this.
questionText.setText(qAndA[i][count]);
count++;
I was trying to make a simple APP that converts between Celsius and Fahrenheit:
I wrote two EditText, one is for input and another is for output, also I have two buttons (toC and toF).
The code is as following:
public class MainActivity extends ActionBarActivity {
private EditText EditText_input;
private EditText EditText_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText_input = (EditText) findViewById(R.id.input);
EditText_output = (EditText) findViewById(R.id.output);
Button toC = (Button) findViewById(R.id.c);
toC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputS = EditText_input.getText().toString();
double inputD = Double.parseDouble(inputS);
double outputD = (5/9) * (inputD-32);
String outputS = String.valueOf(outputD);
//Toast.makeText(MainActivity.this,String.valueOf(outputD),Toast.LENGTH_LONG).show();
EditText_output.setText(outputS, TextView.BufferType.EDITABLE);
}
});
Button toF = (Button) findViewById(R.id.f);
toF.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String inputS = EditText_input.getText().toString();
double inputD = Double.parseDouble(inputS);
double outputD = (9/5) * inputD + 32;
String outputS = String.valueOf(outputD);
EditText_output.setText(outputS, TextView.BufferType.EDITABLE);
}
});
}
After clicking the button toC, it always produces 0.0, and clicking the button toF would produce a wrong result. I set the inputType for the EditText as numerdecimal, I tried number but still doesn't work.
I checked that the problem is from outputD, but I have no idea why outputD can't get a correct result.
Could anyone help me?
When you calculate double outputD = (5/9) * (inputD-32); the compiler assumes that 5 and 9 are ints, so 5/9 is zero. If you want the compiler to treat the numbers as doubles, you should write double outputD = (5.0/9.0) * (inputD-32);. The same applies to the second conversion - double outputD = (9/5) * inputD + 32;
5 and 9 both are integer that is why it always give integer
so 5/9 will always give 0.
Make it
5/9.0
or 5.0/9.0
it will definately work
Compiler treats division (5/9) as a Integer division.
Hence first result is always zero.
You can make one of the number as double like 5.0 or 9.0
double outputD = (5.0/9) * (inputD-32);
Or
double outputD = (5/9.0) * (inputD-32);
Or
double outputD = (5.0/9.0) * (inputD-32);
want to make generic dividing app just to test some stuff out because I'm pretty new at everything still. I get the final number, I just don't know how or where to apply NumberFormat or DecimalFormat or how to properly Math.Round so I only get 2 decimal places as a result. I'll want to spit whatever number divided out back into a text view.
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1 = Integer.parseInt(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Integer.parseInt(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
result.setText(Double.toString(total));
}
});
}
Try using the String.format() method, it will create a string with that number rounded (up or down as appropriate) to two decimal places.
String foo = String.format("%.2f", total);
result.setText(foo);
Try using this code:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
result.setText(df.format(n1 / n2));
Hoping it's work. Thanks
you can use String.format()
result.setText(String.format("%.2f", total));
OR
use Math.round()
Math.round(total*100.0)/100.0
like this:
result.setText(Double.toString(Math.round(total*100.0)/100.0));
You should try this
result.setText(String.format( "%.2f", total) );
I am trying to create an application that returns a score based on user input.
for example if the user has 1000 posts on a specific site it would return 1. i would end it at 10000.
1000 = 1
2000 = 2 etc.
here is what i have so far and thanks. this site is awesome.
for now i just have each entry adding. value1+value2 etc.
public class DataIn extends Activity {
EditText editPostCount;
EditText editThanksCount;
EditText editRomCount;
EditText editThemeCount;
EditText editKernelCount;
EditText editTutorialCount;
EditText editYearsJoined;
Button mButton;
TextView results;
Button mButton1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.data_in);
android.app.ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
editPostCount = (EditText)findViewById(R.id.editPostCount);
editThanksCount = (EditText)findViewById(R.id.editThanksCount);
editRomCount = (EditText)findViewById(R.id.editRomThreads);
results = (TextView)findViewById(R.id.results);
editThemeCount = (EditText)findViewById(R.id.editThemeCount);
editKernelCount = (EditText)findViewById(R.id.editKernelCount);
editTutorialCount = (EditText)findViewById(R.id.editTutorialCount);
editYearsJoined = (EditText)findViewById(R.id.editYearsJoined);
mButton = (Button)findViewById(R.id.results_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
private void calculate() {
try {
Double value1 = Double.parseDouble(editPostCount.getText().toString());
Double value2 = Double.parseDouble(editThanksCount.getText().toString());
Double value3 = Double.parseDouble(editRomCount.getText().toString());
Double value4 = Double.parseDouble(editKernelCount.getText().toString());
Double value5 = Double.parseDouble(editThemeCount.getText().toString());
Double value6 = Double.parseDouble(editYearsJoined.getText().toString());
Double value7 = Double.parseDouble(editTutorialCount.getText().toString());
//do the calculation
Double calculatedValue = (value1+value2+value3+value4+value5+value6+value7);
//set the value to the textView, to display on screen.
results.setText(calculatedValue.toString());
} catch (NumberFormatException e) {
// EditText EtPotential does not contain a valid double
}
mButton1 = (Button)findViewById(R.id.clear_button);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editPostCount.setText("");
editThanksCount.setText("");
editRomCount.setText("");
editThemeCount.setText("");
editKernelCount.setText("");
editTutorialCount.setText("");
editYearsJoined.setText("");
results.setText("");}
});
} }
You can get the score for every value using a simple division, that is cut to an integer.
In this example I also defined one constant to determine for each different value a specific score factor.
private static final int TOTALCOUNT_SCOREFACTOR = 1000;
int totalCountScore = totalCount / TOTALCOUNT_SCOREFACTOR;
I suggest you not to use doubles, generally int is enough.
I also suggest you to use an array of values, instead of defining all of them separately. In that way, you can easily add or remove values in future.
I hope I am not misunderstanding your question, but if you want the score to add 1 point for every 1000 posts, you simply get the number of posts and divide by 1000. for example:
//value1 is the post count
int calculatedvalue = value1/1000;
So if the number of posts(value1) is 3500, calculatedvalue would be 3.(the remainder is cut off during division)