面试的时候回让手写一个函数求最大值、最小值、还有公因数,今天我们来看一下怎么实现。
先看xml布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="20sp"
android:text="输入第一个数:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edit_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="20sp"
android:text="输入第二个数:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edit_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="计算"
android:id="@+id/commit"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="最大公约数为:" />
<TextView
android:id="@+id/number"
android:textColor="#d2d2"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
再看代码实现:
private void submit() {
// validate
String one = edit_one.getText().toString().trim();
if (TextUtils.isEmpty(one)) {
Toast.makeText(this, "one不能为空", Toast.LENGTH_SHORT).show();
return;
}
String to = edit_to.getText().toString().trim();
if (TextUtils.isEmpty(to)) {
Toast.makeText(this, "to不能为空", Toast.LENGTH_SHORT).show();
return;
}
// TODO validate success, do something
//string转int
int i = Integer.parseInt(one);
int i1 = Integer.parseInt(to);
getGCD(i,i1);
}
判断输入的两个值是否为空,不为空则转换为int传入 getGCD()方法进行求值
//求数值的方法
public int getGCD(int x,int y) {// x接受第一个整数,y接受第二个整数
int num=1;// 定义一个变量num,来保存最大公约数
for (int i = 1; i <=x; i++) {// 遍历1到x的所有整数
if (x%i==0 && y%i==0) {// 如果有一个数同时满足被x,y整除
num=i;// 将这个数保存到num变量
//int转string
number.setText(Integer.toString(num));
}
}
return num;
}
求完值在转换为string赋值给TextView。
是不是觉得有点简单呢