简体   繁体   中英

Speedometer Android app not working with km/h conversion?

I am making a speedometer app for a high school science fair that displays a warning message when a speed is exceeded. When my app hits the speed limit, it does not display the message. However when I change the section else if (location.getSpeed() >= (EditNum*3.6)) to else if (location.getSpeed() >= (EditNum)) the app works. The thing is, I don't want to set the limit to MPS. How do I make the app run using the KM/H conversion (*3.6)? PS I am a beginner programmer so sometimes I don't see obvious flaws.

Code:

TextView txt = (TextView) this.findViewById(R.id.textView1); 
TextView war = (TextView) this.findViewById(R.id.textView2); 
TextView war1 = (TextView) this.findViewById(R.id.textView3); 
TextView war2 = (TextView) this.findViewById(R.id.textView4); 
TextView war3 = (TextView) this.findViewById(R.id.textView6);
TextView setLimit = (TextView) this.findViewById(R.id.textView5);

try{
EditText Edit = (EditText) findViewById(R.id.editText1);

String EditValue = Edit.getText().toString();

float EditNum = Float.parseFloat(EditValue);

setLimit.setText("Speed limit: " + (EditNum) + " km/h");


if (location==null)
{
    txt.setText("-.- km/h");
}
else if (location.getSpeed() >= (EditNum*3.6))
{
    war.setTextColor(Color.parseColor("#CC0000"));
    war.setText("Warning!!!"); 
    war1.setText("Speed limit: " + (EditNum*3.6) + " km/h" );
    war2.setText("Speed: " + (location.getSpeed()*3.6) + " km/h");
    war3.setText("Speed limit exceeded by: " + (EditNum*3.6 - location.getSpeed()) + " km/h");
}
else
{
    float nCurrentSpeed = location.getSpeed();
    txt.setText(nCurrentSpeed*3.6 + " km/h");
}
}
catch (NumberFormatException nfe) {
    nfe.printStackTrace();
}

It seems to me that your strategy isn't working out. Looking at it quickly, it seems you might need to divide instead of multiply by 3.6.

Don't confuse what you display with what you compute.

I suggest you run your app in debug mode and add break points (red circles in Android Studio) so that you can look at the value your different variables takes at runtime. You will then understand very easily why certain conditions are met (or not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM