第六课:计算两数的GCF(最大公因数)(基于AndroidStudio3.2)

本例子通过计算两个数字的GCF(最大公因数)来探索如何将数据从主活动传递到第二个活动。

The MainActivity will do the following

  1. Wait for user input (two numbers), so we’ll create two plain text view
    objects
  2. Restrict the inputs to only digits; it doesn’t make sense to accept
    alphanumeric inputs
  3. Check if the text fields are empty; we only want to proceed if they are
    properly filled with numbers
  4. Create an intent, and then we’ll piggyback on that it so we can get
    the two inputted numbers to the Calculate activity

The second activity (Calculate) is the workhorse. It will be the one to do the
number-crunching. Here’s a breakdown of its tasks:

  1. Get the intent that was passed from MainActivity
  2. Check if there’s some data piggybacking on it
  3. If there’s data, we will extract it so we can use it for calculation
  4. When the calculation is done, we will display the results in a text view
    object

About the GCF Algorithm
There are quite a few ways on how to calculate GCF, but the most well-known is probably
Euclid’s algorithm. We will implement it this way.

  1. Get the input of two numbers
  2. Find the larger number
  3. Divide the larger number using the smaller number
     - If the remainder of step no. 3 is zero, then the GCF is the smaller number
     - On the other hand, if the remainder is not zero, do the following:
     ----Assign the value of the smaller number to the larger number, then assign the value of the remainder to the smaller number
     ----Repeat step no. 3 (until the remainder is zero)
    最大公因数的欧几里得算法,当m\leq n时,循环的第一次迭代将它们互换
package programme;
 
public class GratestCommonFactor {
 
	public static void main(String[] args) {
		System.out.println(gcf(1590,1989));
 
	}
	public static long gcf(long m , long n){
		while(n != 0){
			long rem = m % n ;
			m = n ;
			n = rem ;
		}
		return m ;
	}
 
}

一、创建一个GCF项目
1、项目创建后,在activity_main中添加如下控件

  • Plain Text,id:firstno,inputType:number,hint:enter first no,gravity:center
  • Plain Text,id:secondno,inputType:number,hint:enter second no,gravity:center
  • Button,id:button,text:calculate,gravity:center
    在这里插入图片描述

2、新建第二个activity
在项目工具窗口中,右键单击app➤New ➤ Activity ➤Empty Activity。Activity name: Calculate
在这里插入图片描述
完成后在activity_calculate中添加textView控件,gravity:center。
在这里插入图片描述

现在我们已经有了基本的UI设计,让我们来看看我们如何编写代码访问了这些用户界面元素。

3、MainActivity.java

package com.example.administrator.gcf;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText fno;
    private EditText sno;
    private Button btn;

    private final String TAG = "GCF app ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fno = (EditText) findViewById(R.id.firstno);
        sno = (EditText) findViewById(R.id.secondno);
        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Log.i(TAG, "onStart method");
        fno.setText("");
        sno.setText("");
    }

    public void onClick(View v) {
        Log.i(TAG, "onCick of button ");

/*
TextUtils can check if a TextView object doesn’t have any text inside it. You can check for an
empty text field some other way by extracting the string inside it and checking if the length is
greater than zero, but TextUtils is a more succinct way to do it
*/
        boolean a = TextUtils.isEmpty(fno.getText());
        boolean b = TextUtils.isEmpty(sno.getText());

        //Let’s make sure that both text fields are not empty.
        if (!a & !b) {
/*
The getText() method returns an Editable object, which is not compatible with the parseInt
method of the Integer class. The toString method should convert the Editable object to a
regular String
*/
            int firstnumber = Integer.parseInt(fno.getText().toString());
            int secondnumber = Integer.parseInt(sno.getText().toString());

/*
This line creates an Intent object. The first argument to the Intent constructor is a context object.
The intent needs to know from where it is being launched, hence the this keyword; we are
launching the intent from ourselves (MainActivity). The second argument to the constructor is
the target activity that we want to launch
*/
            Intent intent = new Intent(this, Calculate.class);
/*
We are going to piggyback some data into the intent object, so we will need a container for this
data. A Bundle object is like a dictionary; it stores data in key/value pairs
*/
            Bundle bundle = new Bundle();
/*
The Bundle object supports a bunch of put methods that take care of populating the bundle. The
Bundle can store a variety of data, not only integers. If we wanted to put a string into the Bundle,
we could say bundle.putString() or bundle.putBoolean() if we wanted to store boolean data
*/
            bundle.putInt("fno", firstnumber);
            bundle.putInt("sno", secondnumber);
/*
After we’ve populated the Bundleobject, we can now piggyback on the Intent object by calling
the putExtra method. Similar to Bundle object, the Intent also uses the key/value pair for
populating and accessing the extras. In this case, “gcfdata”. We need to use the same key later
(in the second activity) to retrieve the bundle
*/
            intent.putExtra("gcfdata", bundle);
            //This statement will launch the Activity
            startActivity(intent);

            Log.i(TAG, "" + firstnumber);
            Log.i(TAG, "" + secondnumber);

        }
    }
}

4、Calculate.java
MainActivity.java只负责输入和启动Calculateactivity。 GCF的实际工作发生在Calculateactivity内部。

package com.example.administrator.gcf;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Calculate extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculate);

        int bigno, smallno = 0;
        int rem = 1;

        TextView gcftext = (TextView) findViewById(R.id.textView);
/*
This code will be called inside the onCreate method of the Calculate activity; the getIntent
statement here will return whatever was the intent object that was used to launch this activity
*/
        Intent intent = getIntent();
/*
The getBundleExtra returns the bundle object which we passed to the intent object in
MainActivity. Remember that when we inserted the bundle object in MainActivity, we used the
key “gcfdata”; hence, we need to use the same key here in extracting the bundle
*/
        Bundle bundle = intent.getBundleExtra("gcfdata");


        if ((bundle != null) & !bundle.isEmpty()) {
/*
Once we have successfully extracted the bundle, we can get the two integer values that we
stashed in it earlier.
*/
            int first = bundle.getInt("fno", 1);
            int second = bundle.getInt("sno", 1);


            if (first > second ) {
                bigno = first;
                smallno = second;
            }
            else {
                bigno = second;
                smallno = first;
            }

            while ((rem = bigno % smallno) != 0) {
                bigno = smallno;
                smallno = rem;
            }
            gcftext.setText(String.format("GCF = %d", smallno));
        }

    }
}

5、运行ok
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gumufuyun/article/details/83060549
今日推荐