本例子通过计算两个数字的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 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 ";@Overrideprotected 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);}@Overrideprotected 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 ActivitystartActivity(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 {@Overrideprotected 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

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

  1. linux-shell脚本-利用shell函数计算两数之和--思考return原理

    一.实例1(错误代码) 在shell脚本的学习过程中,遇到定义一个带有return语句的函数,来计算两数之和,代码如下: #!/bin/bash funWithReturn(){echo " ...

  2. 用位运算计算两数的和

    用位运算计算两数的和 文章目录 用位运算计算两数的和 方法一: 方法二: 方法一: //方法一: //sum为计算结果 //carry为进位 int bitAdd(int a, int b) {if ...

  3. 用函数计算两数之和和两数之积

    函数的优点 函数是面向过程编写的最重要的语法结构 在工程上函数可以使我们的代码更具有结构性,更加美观 函数也可以提升我们的代码可维护性 运用函数计算两数之和和两数乘积 int MyAdd(int _x ...

  4. 编写函数求两个数的最大公约数,采用递归法计算两数的最大公约数。

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 题目: [实验案例3:函数的递归调用] 编写函数求两个数的最大公约数,采用递归法计算两数的最大公约数. [实验指导] 分析:m.n为两 ...

  5. 【计算两数之和】不使用加减乘除

    计算两数之和不论在计算机中还是生活中,都不算难(即使某些数据过大).但是如何能更高效的计算时一个难题,或者说在计算机内部是如何解析两个数之间的加法的,这就成了一个可以探讨的问题. 当然我们很了解十进制 ...

  6. 6-1 计算两数的和与差 (10 分)

    6-1 计算两数的和与差 (10 分) 本题要求实现一个计算输入的两数的和与差的简单函数. 函数接口定义: void sum_diff( float op1, float op2, float *ps ...

  7. 微型计算机原理计算两数和,微型计算机原理及汇编语言 第2章-2 补码及加减运算.ppt...

    微型计算机原理及汇编语言 第2章-2 补码及加减运算 2.4 数的定点与浮点表示法 2.4.1 定点表示 所谓定点表示法,是指小数点在数中的位置是固定的.原理上讲,小数点的位置固定在哪一位都是可以的, ...

  8. 【Java】编写Java程序,完成从键盘输入两个运算数据,计算两数之和并输出结果...

    public class MyTest {public static void main(String[] args) {int a=2;int b=6;int c=a+b;System.out.pr ...

  9. 不使用算术运算符计算两数之和

    计算两个数之和,本来是一件小学生就会做的事,不对,幼儿园学生都会!可是偏偏有些面试官,要求计算两个数之和不能用加号"+",这不是故意刁难人嘛.可是为了offer,还是得硬着头皮去做 ...

  10. 数组计算两数之和,三数之和,四数之和

    这种计算几个数据之和的题目, 一般分为 在同一个数组中计算几个数之和等于某一个值. 还有一种是给几个数组,每个数组中取一个数据,让你算几个数之和等于某一个值. 一般情况下,第二中的难度会更大,因为去重 ...

最新文章

  1. 为何Google将几十亿行源代码放在一个仓库?| CSDN博文精选
  2. Algorithms_基础数据结构(02)_线性表之链表_单向链表
  3. 面试中一个暴露能力等级的问题
  4. C# 方法中的this参数
  5. JUC.Condition学习笔记[附详细源码解析]
  6. 2.2_ 4_ FCFS、SJF、 HRRN调度算法
  7. spark-sql建表语句限制_SparkSQL
  8. CMD(命令提示符)-------javac编译程序出现“”编码GBK的不可映射字符“”
  9. webpack之react开发前准备
  10. 2.4 表单数据的验证
  11. 微电子学与计算机模板,微电子学专业个人简历模板
  12. 公众号运营工具有哪些?
  13. autojs开发的多功能工具箱,源码量大慢慢消化,功能非常多
  14. 专访阿里云褚霸等--挖掘数据库核心价值
  15. 中兴2016笔试题答案Java_中兴Java笔试题
  16. 计算机不能连接网络适配器,网络适配器显示未连接的解决方法图文教程
  17. Dell 灵越7559笔记本电脑加M.2固态硬盘
  18. 探索语言交互技术在政务数字化的应用
  19. Xshell7.0/Xftp7.0官方免激活下载
  20. 【TeamViewer丨远程控制软件】上海道宁助您远程访问和即时远程支持,提高远程工作团队的生产力

热门文章

  1. 产品设计:Material Design 学习笔记一
  2. w7计算机超级管理员权限,win7系统取得管理员最高权限的操作方法
  3. Hibernate表间映射时HHH000142异常
  4. CNI网络插件之flannel
  5. 这次跟大家聊聊技术,也聊聊人生
  6. MTK-EIS电子防抖-gyro校准
  7. 【MTK AF】Acce/Gyro/PD/Laser Driver Check
  8. ISIS metric
  9. c语言开发 kdj,[转载]随机指标KDJ,及其MA、EMA、SMA、DMA介绍
  10. 编程入门书籍:大学学习计算机基础必读 5 本经典入门书籍,收藏