安卓studio模拟电费计算,输入用电量显示电费
时间: 2024-03-24 14:38:38 浏览: 33
好的,我可以帮你实现这个功能。你需要在安卓studio中创建一个布局文件来设计用户输入用电量的界面,并创建一个Java类来处理电费计算的逻辑。以下是一个简单的示例代码:
布局文件(activity_main.xml):
```xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用电量" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="计算电费" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="电费:" />
</LinearLayout>
```
Java类(MainActivity.java):
```java
public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String input = editText.getText().toString().trim();
if (!TextUtils.isEmpty(input)) {
double electricity = Double.parseDouble(input);
double price = calculatePrice(electricity);
textView.setText("电费:" + price + "元");
} else {
Toast.makeText(MainActivity.this, "请输入用电量", Toast.LENGTH_SHORT).show();
}
}
});
}
private double calculatePrice(double electricity) {
double price = 0;
if (electricity <= 100) {
price = electricity * 0.5;
} else if (electricity <= 200) {
price = 100 * 0.5 + (electricity - 100) * 0.6;
} else {
price = 100 * 0.5 + 100 * 0.6 + (electricity - 200) * 0.7;
}
return price;
}
}
```
这段代码会在用户输入用电量后,根据不同的电价计算出电费,并显示在界面上。注意,这只是一个简化的示例,实际的电价计算可能会更加复杂。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)