EECS1022 Android入门教程

2016-01-06 17:43:33

[专业笔记 | Academic]

主要是上课的笔记,尽量尝试一下周更吧。内容会比较偏向于应试方面。

选这门课主要还是凑学分刷绩点吧,所以这里写的很多其实大家都明白,但是考试要是真是要考可能就记不起来的内容。

 

 

Lecture 1

 

EECS 1022  Prof Roumani - York Univeristy

  • Separation of Concerns
  • Industrial-Strength Tools
  • IoT  Internet of Things

 

ELOs 课程评价方式

  1. 基本的程序设计
  2. UI和Java的连接
  3. 建造App使用现有API
  4. OOP
  5. 使用简单的OOP,Observing S/E 标准
  6. 集合、文件、正则表达式

 

疑问:Moodle -> Form
每周都有实验

 

关于变量的命名方式

  • XML采用Pascal的方式定义          ThisIsTheVariable
  • Java 在变量方面使用OC相同的Camel方式定义 thisIsTheVariable
  • 但是Java在Class名称方面喜欢使用Pascal方式命名Class Name: PASCAL
    Method Name: Camel
    Block: {}在同一列

 

各种词语的定义

  • Attributes函数中的参数
  • Keywords关键字
  • Identifiers变量的名称
  • Literals可用于变量的值,硬编码的值

 

文档目录结构

  • manifests——权限相关
  • java——layout还有代码

 

本课程适用Android  Studio作为编程的工具

程序的结构Component Tree—— 顶端是Linear Layout

值可以refer到strings.xml ,使用Resources连接

 

Android的MVC 设计思路:

  • Module: POJO. Plain Old Java Object. Java Object (Class)
  • View: XML.
  • Control: Java. but Activity

Java的网站的MVC设计思路

  • Module: POJO
  • View: JSP,ASP
  • Control: Servlet

 

Java final keyword

  • 类似于Swift 的 let关键字
  • Final means cannot re-assign value to any variable
  • Static means only one copy of reference can be in hole in the class of all methods.

 

Doing things fast
Stand alone obj 可以方便调试,使用对单个Java文件采用Run as main(右键菜单),定义一个main function.

public static void main(String[] args){

}

 

 

 

 

Lecture 2

import some class

import java.lang.System;
  • package: java
  • subpackage: lang
  • class: System

 

Java--(Compile)-->Bytecode--(Run)-->App

Compile: Syntax Errors
Run: Runtime Errors
Compute Wrong Result: Logic Errors

 

 

 

 

Week 1 Review

双重虚拟机相当的慢,类似OC Delegate的方法能够自动填充delegate的方法。

 

 

 

Lecture 3

到了第二周,这些课都是讲一些非常基础的内容。下周会有一个Quiz,可以在课室使用网络完成,也可以使用答题卡完成。

Attributes (Global variables)
Constructors

For Method

  • name: Compute
  • params: int, double
  • Above all are Signature

Overloaded, method的name是相同的

int +- 2G 4byte
long +- 2E 8byte
float +- 10^38 Significant Digits = 7
double +- 10^308 Significant Digits = 15

Accuracy is Significant Digits.

Constant 采用 THIS_WAY_TO_DEFINE

Boolean Type

  • g = x ^ y 为XOR 运算
  • 左移( << )、右移( >> ) 、无符号右移( >>> ) 、位与( & ) 、位或( | )、位非( ~ )、位异或( ^ ),除了位非( ~ )是一元操作符外,其它的都是二元操作符。

符号

  • Parentheses ()
  • Bracket []
  • Braces {}

运算顺序(即使有类型转换,也要遵守这个运算顺序)

  1. ()
  2. */%
  3. +-
double t = 2 / 5 - 1.0; //Answer is -1.0

int sum = 45;
int count = 10;
double average = (double) sum / count; //force cast
double average = sum / count; //DO NOT DO THAT

在运算符号的左右,如果其中任何一个是浮点值,则运算结果为浮点值;如果两者都不是浮点值,则为整型。

printf() print something with formating

  • %d decimal
  • %f

 

 

 

 

Lecture 4

Unicode 64K codes

SCAII

  • A 65
  • ZERO 48
  • space 32
  • a 97

Relational Operators

  • Requirements
  • Design
  • Implementation
  • Testing
  • Deployment

Project Satellite Orbital Period

  • Requirement Analysis
    • Significant Digits
    • The format of output
  • Design
  • Implementation
  • Testing
  • Deployment

 

 

 

 

Week 2 Review

在自己定义的Class中添加toString() 可以在调试的情况下,让程序自动标记Object的名称

public class ComputeEngine
{
    public String toString()
    {
        return "The Compute Engine!";
    }
}

 

 

Lecture 5

下节课考试。

定义科学计数法

public static final double G = 6.67408e-11;
public static final double M = 5.972e24;
public static final double R = 6371e3;

Math Library

Math.pow(number, 0.5);
Math.sqrt(number);

 

 

 

 

Lecture 6

Typically, class don't have main() method except the UI class.

String.format("%.1f", sec);

Object

  • state
  • object

 

 

 

 

Lecture 7

new  代表创建一个object,new 关键字  copy 一个class的定义将其布置到object里面。

Heap https://en.wikipedia.org/wiki/Heap_(data_structure)

Stack https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

注意这些的区别

  • Object reference (数指向object的指针)
  • identical Object (内容一样)
  • Objects in memory (数 new 关键字)

对比Object的内在值(检查),使用默认(Default)的equals()函数需要注意。一般情况需要自己在Class中定义equal()

boolean b5 = sat2.equals(sat5);
System.out.printf("===> %b \n", b5);
public boolean equals(Object x){
  this.altitude == ((Satellite) x).altitude;
}

同样的Default的函数还有  toString()

如果需要可以override 这个 toString(),当然不需要以下关键字

@Override

如果定义为static,对象将会依赖于 Class 而不是Object

public static int testtest = 1000;

 

 

 

 

Lecture 8

例子

package jba.roumani.sandbox1;

public class cStaticTest{
    private static int idnumber = 0;

    public cStaticTest(){
        idnumber ++;
    }

    public void showIDNumber(){
        System.out.printf("id==>%d \n", idnumber);
    }

    public static void main(String[] args) {
        cStaticTest t1 = new cStaticTest();
        t1.showIDNumber(); //输出1
        cStaticTest t2 = new cStaticTest();
        cStaticTest t3 = new cStaticTest();
        cStaticTest t4 = new cStaticTest();
        t3.showIDNumber(); //输出4
        t2.showIDNumber(); //输出4
    }
}

正确的解决方法应该使用以下函数。

package jba.roumani.sandbox1;

public class cStaticTest{
    //声明区域
    private static int lastIDNumber = 0;
    private int idnumber = lastIDNumber + 1;

    //初始化
    public cStaticTest(){
        lastIDNumber ++;
        System.out.printf("obj Created==>(%d,%d) \n", idnumber, lastIDNumber);
    }

    public void showIDNumber(){
        System.out.printf("id==>%d \n", idnumber);
    }

    public static void main(String[] args) {
        cStaticTest t1 = new cStaticTest();
        t1.showIDNumber();
        cStaticTest t2 = new cStaticTest();
        cStaticTest t3 = new cStaticTest();
        cStaticTest t4 = new cStaticTest();
        t3.showIDNumber();
        t2.showIDNumber();
    }
}

从输出结果可以看出,声明区域将早于初始化函数执行。

关于  java.util.Date
epoch Jan 1, 1970 12:00 AM GMT

https://docs.oracle.com/javase/6/docs/api/java/util/Date.html

 

 

 

 

Lab test 1

Period: one hour

CLR, TONE, ROCK

Question will be asked to change those lab works.

关于Submission

https://webapp.eecs.yorku.ca/submit/

 

 

 

 

Lecture 9

Control Structures.

  • sequence 顺序结构
  • selection 选择结构
  • iteration 循环结构
if (TrueOrFalse) {
//CODE
}

for (beforeTheLoop; stayBooleanCheckBeforeLoop; endOfEachLoop){
//CODE
}

对于本课程,创建符合要求的新工程最简单的方法是复制LOL

 

 

 

 

Lecture 10

 

<EditText
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:inputType="number"
 android:ems="10"
 android:id="@+id/editText"
 android:layout_below="@+id/textView"
 android:layout_alignParentRight="true"
 android:numeric="decimal"
 android:layout_alignParentEnd="true" />

 

菜单中 Code->Reformat Code...可以整理代码

 

输出格式(高额金额的输出格式)

double income = 819723287.22; 
System.out.printf("%,15.2f", income);

 

 

 

Lecture 11

 

提取TextView内容

 

@Override
public void onClick(View v)
{
    if (v.getId() == R.id.tableBtn){

        String in1 = ((EditText) findViewById(R.id.input1)).getText().toString();
        String in2 = ((EditText) findViewById(R.id.input2)).getText().toString();
        double principle = Double.parseDouble(in1);//转为Double型
        int row = Integer.parseInt(in1);//转为Integer型

        // 1. get the interest rate
        // 2. Create a Morgage instance
        // 3. get the monthly payment
        // 4. round the monthly payment to dollars and cents (use String.format)
        // 5. find the output1 text viee and set its text to the rounded payment
    }
}

 

 

Use of scrollView

scrollView 可以内含 LinearLayout 这样可以确保组内元素的有序性

 

如果要求中含有 take as precondition 可以不用验证数据

boolean prime = true;
for (int i = 2; i < n && prime; i ++)
{
  if (n % i == 0)
  {
    prime = false;
  }
}

 

 

Lecture 12

String s = "York EECS";
//是语法糖,并且是Immutable
//实际,会转化为:
String s = new String("York EECS");


//语法糖
String a = "HELLO";
String b = "WORLD";

String m = a + b;
//实际上是使用了concat方法

String s = "York";
s.toUpperCase();
System.out.print(s); //输出 York

s = s.toUpperCase();
System.out.print(s); //输出 YORK

 

do documentation

Java 和 C系列语言一样,String应该用equal函数进行比较。

 

Test1 Review

 

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        System.out.println("onSaveInstanceState called");
        super.onSaveInstanceState(outState);

        TextView convertedText = (TextView) findViewById(R.id.convertedText);
        EditText editText = (EditText) findViewById(R.id.inputText);

        outState.putSerializable("converted", convertedText.getText().toString());
        outState.putSerializable("original", editText.getText().toString());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        System.out.println("onRestoreInstanceState called");
        super.onRestoreInstanceState(savedInstanceState);

        TextView convertedText = (TextView) findViewById(R.id.convertedText);
        EditText editText = (EditText) findViewById(R.id.inputText);

        convertedText.setText((String) savedInstanceState.getSerializable("converted"));
        editText.setText((String) savedInstanceState.getSerializable("original"));
    }

 

 

Lecture 13

  • Math.pow(底,指数)
    • 注意指数可能会被取整
  • Math.sqrt()
  • Math.cbrt()

 

Formatted Output 的几个例子

    public static void main(String[] args) {
        char temp = 'A';
        System.out.printf("%c-%d", temp, (int) temp); //输出: A-65 需要强制转换temp,否则报错

        int zNumber = 2222223;
        System.out.printf("%d%n",zNumber);      //输出:2222223
        System.out.printf("%010d%n", zNumber);  //输出:0002222223
        System.out.printf("%10d%n", zNumber);   //输出:___2222223
        System.out.printf("%,10d%n", zNumber);  //输出:_ 2,222,223

        double dNumber = 1123.45678;
        System.out.printf("%f%n", dNumber);     //输出:1123.456780
        System.out.printf("%010.2f%n", dNumber);//输出:0001123.46
        System.out.printf("%10.2f%n", dNumber); //输出:___1123.46
        System.out.printf("%,10.2f%n", dNumber);//输出:__1,123.46
    }

\%(\,)?((0)?\d+)?d

\%(\,)?((0)?\d+)?(\.\d+)?f

 

字符串的基本操作

  • String.substring(开始位置,结束位置) 包含开始位置,结束位置将不包含
  • String.charAt(位置)
  • String.length() 获取字符串长度

 

如果是仅仅包含数字的字符串

  • + coercion
    • charNumber + "0" = Char
  • parse
    •  Integer.parseInt(字符串)
    •  Double.parseDouble(字符串)
  • char minus '0'

字符串的变形

  • toLowerCase()
  • toUpperCase()
  • trim()

字符串的比较

  • equals()
  • compareTo()
    • 比较两个字符串的的字符大小
    • 主要看正负,用于英文字符串的排序
    • 返回数字
  • empty的字符串还是 null的字符串
    • 如果null:s.length() 将会给出错误

片段处理

  • indexOf(需要查找的字符)
  • indexOf() with offset
  • replaceAll()

Lecture 14

正则表达式

加拿大邮编  ([A-VXYa-vxy][0-9][A-Za-z] *[0-9][A-Za-z][0-9])

public String analyze(String str){
        Pattern compiledPattern = Pattern.compile(this.regex);
        Matcher patternMatches = compiledPattern.matcher(str);

        String answer = "";

        while (patternMatches.find()) {
            //找到了
            for (int i = 0; i <= patternMatches.groupCount(); i++) {
                answer += String.format("%s, at %d, %d\n",
                        patternMatches.group(i),//返回选中的字符串,从1开始,零将返回整个字符串
                        patternMatches.start(i),
                        patternMatches.end(i)
                );
            }
        }
        return answer;

}

 

Lecture 15

回去验证一下 pattern.find() 这是一个指针,没有利用group()的方法,两个应该是独立的,不应该相互使用

  • Regex
    • Matches:
      • 包含find()
    • Groups:
      • 包含group() groupCount()
      • 将返回正则表达式中括号匹配的内容
      • group(0) 将返回find() 的内容
      • group(N) N >=1 将安顺序返回正则表达式中括号的内容

 

字符串比较可以使用  x.equals(y) 或者 x.equalsIgnoreCase(y)

    public static void main(String[] args)
    {
        String sentence = "she Asell Bseashells Con Dthe EseashoreF sunG shine H.";
        String[] tokens = sentence.split("s[a-z]* ");
        for (int i = 0; i<tokens.length; i++){
            System.out.println(i+")"+tokens[i]);
        }

        //输出:
        //0)
        //1)A
        //2)B
        //3)Con Dthe EseashoreF sunG
        //4)H.
    }

 

 

Lecture 16

Collections Framework

Aggregation (集合) 将多个Object存储到一个object中

  • Array 是 Static Allocation 并且没有API
  • 一些集合的(Aggregation)数据结构有 Interfaces例如 List<E>, Set<E>, Map <K,V>

 

  • List : 允许重复,有序
    • ArrayList 更类似Array
    • LinkedList 更便于插入,使用指针存储
  • Set : No duplicates, No order,使用.equals 比较Object(待查)
    • HashSet 是无序的
    • TreeSet 是有序的(sorted)使用.compareTo() 来排序
  • Map :  Key and Value
    • HashMap 是无序的
    • TreeMap 是有序的(sorted)使用.compareTo() 来排序

 

API 关于这些Aggregation的APIs

  • size()
  • clear()
  • iterator()

 

Lecture 17

注意使用 Code -> Code Generate 来创建默认的函数,例如:

  • constractor
  • Getter / Setter
  • toString()
  • equals()
  • compareTo()

 

Lecture 18

Toast.makeText(显示对象,字符串,时间);

显示对象为this.getApplicationContext()

 

 

Lecture 19

Pick up class test #1 in WSC(lab) next week

  • Basic
    • size()
    • clear()
    • iterator() reach each elements in the collection
  • Set
    • add(E)
    • remove(E)
    • contains(E)
  • List
    • add(int, E) 从零开始,到字符串长度,如果int是[0,length]以外的值就出错
    • remove(int)  从零开始,如果移除失败则抛出错误
    • get(int) 从零开始,如果获取失败则抛出错误
    • contains(E)
  • Map
    • put(K, V) 相同Key 会覆盖,后面的值覆盖前面
    • get(K) 获取Key对应的值
    • keySet() 获取一个由Map键值为类型的Set
    • containsKey(K) 检查是否有键
    • containsValue(V) 检查是否有值
    • remove(K) 填入键名,如果不存在不回抛出错误
  • Other API (import java.util.Collections;)
    • f(type item:collection)()
    • Collections.sort(List) Only Accept List
    • Collections 更多函数

 

Set 无法使用index,因此无法进行随机访问

回去复习这些API的用法,做幻灯片里面的练习。老师上课讲错了。。。

 

Lecture 20

Exception Handling

  • Pre Condition (相当于没有防御)
  • Defensive(使用if,可预见的例外)
  • Exception(不可见例外)

 

try{	
//内容
}catch(Exception e){
	result = -1.0;
	System.out.println(e.getMessage());
	e.printStackTrace();
}

 

 

Lecture 21

public static enum SortType {COUNTRY, CAPITAL, POP};

 

 

这篇博文发表在 专业笔记 | Academic 目录下,标签为
如需引用,请使用链接:https://note.mc256.dev/?p=845

This article published in 专业笔记 | Academic with tags .
Cite this page using this link:https://note.mc256.dev/?p=845

您的邮箱地址不会被公开,评论使用Gravatar头像。
Your email address will not be published. This blog is using Gravatar.

正在提交评论... Submitting ...
正在为您准备评论控件 Loading Comment Plugin
Copyright © 2013-2023 mc256. All Rights Reserved.
Powered by WordPress on top of a dual-stack k3s Cluster using JuiceFS.
Wordpress Theme Designed By mc256.
Encrypted By Let's Encrypt.  Hosted On Linode + OVH + AWS.
DNS Provided By Hostker.
Status Page by CloudFlare Worker.