First Android App
I'm fairly new to the whole android scene, and I decided to start off with something simple, a Celsius to Fahrenheit converter. Here's the block of code I'm using to do the actual math (x-32)*5/9 where x=input for Celsius Temp.
convertbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
double result = ne开发者_如何学JAVAw Double(input.getText().toString())-32*5/9;
output.setText(Double.toString(result));
I know that x-32*5/9 is not a valid way to do the (x-32)*5/9 formula, but I can't put the -32 in parenthesis. Just looking for ways to get it to subtract 32 from the input first, and then for it to multiply that by 5/9. Any help would be much obliged.
You may have been confused by the parentheses in this expression:
new Double(input.getText().toString())-32*5/9
It would work if you parenthesized the whole thing up to 32:
(new Double(input.getText().toString())-32)*5/9
^ here and here ^
But it’s easier to read if you put the value in a temporary variable:
double input_value = new Double(input.getText().toString());
double result = (input_value - 32) * 5/9;
You are probably looking for Double.parseDouble(String);
Here is an example...
String s = "56.7";
double input = Double.parseDouble(s);
input = (input - 32d) * (5d/9d);
Edit: the d is necessary to force java to interpret the constants as doubles
精彩评论