极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

楼主: yangfanconan

Processing之旅-----【3课数据类型,Processing世界的居民】

[复制链接]
发表于 2013-5-8 09:28:06 | 显示全部楼层 |阅读模式
本帖最后由 yangfanconan 于 2013-5-8 09:32 编辑

上课!
同学们今天这节课,我们主讲Processing的数据类型。

Processing的数据类型包括基本类型(Primitive):boolean,byte,char,color,double,float,int,long。
还包括一些数据结构(Composite):Array,ArrayList,HashMap,Object,String,Table,XML。

首先让我们了解一下基本类型。


boolean(布尔类型):
描述:
是布尔值的数据类型的值。常见的使用布尔值来确定程序流控制语句。第一次写入变量,它必须声明,表示它的数据类型。
语法:
boolean varboolean var = booleanvalue
例子:
  1. boolean a = false;
  2. if (!a) {
  3.   rect(30, 20, 50, 50);
  4. }
  5. a = true;
  6. if (a) {
  7.   line(20, 10, 90, 80);
  8.   line(20, 80, 90, 10);
  9. }
复制代码

byte(字节类型)
描述:字节数据类型,拥有8位二进制位物理空间,8位信息存储数值从127到-128。字节是一个方便的发送信息,并从串行端口的数据类型和代表字符(char)数据类型比一个简单的格式。第一次写入变量,它必须声明,表示它的数据类型。
语法:
byte varbyte var = value
例子:
  1. // Declare variable 'a' of type byte
  2. byte a;

  3. // Assign 23 to 'a'
  4. a = 23;

  5. // Declare variable 'b' and assign it the value -128
  6. byte b = -128;

  7. // Declare variable 'c' and assign it the sum of 'a' and 'b'.
  8. // By default, when two bytes are added, they are converted
  9. // to an integer. To keep the answer as a byte, cast them
  10. // to a byte with the byte() conversion function
  11. byte c = byte(a + b);
复制代码

char(字符类型):
描述:char是整型数据中比较古怪的一个,其它的如int/long/short等不指定signed/unsigned时都默认是signed,但char在标准中是unsigned,编译器可以实现为带符号的,也可以实现为不带符号的,有些编译器如pSOS的编译器,还可以通过编译开关来指定它是有符号数还是无符号数。
语法:
char varchar var = value
例子:
  1. char m;      // Declare variable 'm' of type char
  2. m = 'A';     // Assign 'm' the value "A"
  3. int n = '&'; // Declare variable 'n' and assign it the value "&"
复制代码

color(颜色类型):
描述:颜色类型是存储颜色值的数据类型。一个color类型占用32位二进制数据位。其格式为(AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB )其中A为透明度,R是红色,G是绿色,B是蓝色。
语法:
color c = #006699
color c1 = color(204, 153, 0);
color c2= color(100,0,100,158);
例子:
  1. color c1 = color(204, 153, 0);
  2. color c2 = #FFCC00;
  3. noStroke();
  4. fill(c1);
  5. rect(0, 0, 25, 100);
  6. fill(c2);
  7. rect(25, 0, 25, 100);
  8. color c3 = get(10, 50);
  9. fill(c3);
  10. rect(50, 0, 50, 100);
复制代码

float(浮点数类型):
描述:float类型中小数位数为7位,即可精确到小数点后7位,表示范围为1.5e - 45~ 3.4e + 38。
语法:
float varfloat var = value
例子:
  1. float a;           // Declare variable 'a' of type float
  2. a = 1.5387;        // Assign 'a' the value 1.5387
  3. float b = -2.984;  // Declare variable 'b' and assign it the value -2.984
  4. float c = a + b;   // Declare variable 'c' and assign it the sum of 'a' and 'b'
  5. float f = 0;
  6. for (int i = 0 ; i < 100000; i++) {  
  7.   f = f + 0.0001;  // Bad idea! See below.
  8. }

  9. for (int i = 0; i < 100000; i++) {
  10.   // The variable 'f' will work better here, less affected by rounding
  11.   float f = i / 1000.0;  // Count by thousandths
  12. }
复制代码

double(双精度浮点数类型)
描述:double(双精度浮点型)是计算机使用的一种资料型别。比起单精度浮点数(float),double(双精度浮点数)使用 64 位(8字节) 来储存一个浮点数。 它可以表示十进制的15或16位有效数字,负值取值范围为 -1.7976E+308 到 -4.94065645841246544E-324,正值取值范围为 4.94065645841246544E-324 到 1.797693E+308
语法:
double vardouble var = value
例子:
  1. double a;            // Declare variable 'a' of type float
  2. a = 1.5387;          // Assign 'a' the value 1.5387
  3. double b = -2.984;   // Declare variable 'b' and assign it the value -2.984
  4. double c = a + b;    // Declare variable 'c' and assign it the sum of 'a' and 'b'
  5. float f = (float)c;  // Converts the value of 'c' from a double to a float
复制代码

int(整型类型):
描述:不带小数点的整数,数字数据类型。整数可以一样大2,147,483,647和低至-2,147,483,648的。它们被存储为32位的信息。第一次写入变量,它必须声明,声明,表示它的数据类型。
语法:
int varint var = value
例子:
  1. int a;          // Declare variable 'a' of type int
  2. a = 23;         // Assign 'a' the value 23
  3. int b = -256;   // Declare variable 'b' and assign it the value -256
  4. int c = a + b;  // Declare variable 'c' and assign it the sum of 'a' and 'b'
复制代码

long(长整型类型)
描述:整数-9,223,372,036,854,775,808的最小值和最大值9,223,372,036,854,775,807(存储为64位)。
语法:
long varlong var = value
例子:
  1. long a;          // Declare variable 'a' of type long
  2. a = 23;          // Assign 'a' the value 23
  3. long b = -256;   // Declare variable 'b' and assign it the value -256
  4. long c = a + b;  // Declare variable 'c' and assign it the sum of 'a' and 'b'
  5. int i = (int)c;  // Converts the value of 'c' from a long to an int
复制代码

下面我们开始学习Processing中提供的数据类型

Array(数组):
描述:数组是在程序设计中,为了处理方便, 把具有相同类型的若干变量按有序的形式组织起来的一种形式。这些按序排列的同类数据元素的集合称为数组。需要注意到是数组下标是从0开始的。例如您声明了一个数组int [100]m_iarray;此100是指有100个元素,
而不是下标可以指到100,数组是非常高效但危险的数据结构,希望大家自习理解多多练习。
语法:
datatype[] var //例如int []m_iarrayvar[element] = value //例如int [100]m_iarray=avar.length
例子:

  1. int[] numbers = new int[3];
  2. numbers[0] = 90;  // Assign value to first element in the array
  3. numbers[1] = 150; // Assign value to second element in the array
  4. numbers[2] = 30;  // Assign value to third element in the array
  5. int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240
  6. int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180
  7. int[] numbers = { 90, 150, 30 };  // Alternate syntax
  8. int a = numbers[0] + numbers[1];  // Sets variable 'a' to 240
  9. int b = numbers[1] + numbers[2];  // Sets variable 'b' to 180
  10. int degrees = 360;
  11. float[] cos_vals = new float[degrees];
  12. // Use a for() loop to quickly iterate
  13. // through all values in an array.
  14. for (int i=0; i < degrees; i++) {         
  15.   cos_vals[i] = cos(TWO_PI/degrees * i);
  16. }
复制代码


ArrayList(链表):
描述:
ArrayList中存储可变数目的对象。这是一个对象数组类似,但与一个ArrayList,项目可以很容易地添加和删除从ArrayList,它是动态调整大小。这可以非常方便的,但它的速度比一个对象数组时使用的许多元素。 ArrayList是一个可调整大小的数组实现Java列表界面。它有许多用于控制和搜索其内容的方法。例如,ArrayList的长度,则返回其大小()方法,这是列表中的元素的总数的整数值。一个元素被添加到一个ArrayList 的add()方法删除()方法被删除。的get()方法返回的元素在列表中的指定位置。(见上面的例子中的上下文。) 众多的ArrayList功能的列表,请参阅Java参考说明

语法:
ArrayList()ArrayList(initialCapacity)
例子:
  1.         
  2. // This is a code fragment that shows how to use an ArrayList.
  3. // It won't compile because it's missing the Ball class.

  4. ArrayList balls;

  5. void setup() {
  6.   size(200, 200);
  7.   balls = new ArrayList();  // Create an empty ArrayList
  8.   balls.add(new Ball(width/2, 0, 48));  // Start by adding one element
  9. }

  10. void draw() {
  11.   background(255);

  12.   // With an array, we say balls.length. With an ArrayList,
  13.   // we say balls.size(). The length of an ArrayList is dynamic.
  14.   // Notice how we are looping through the ArrayList backwards.
  15.   // This is because we are deleting elements from the list.
  16.   for (int i = balls.size()-1; i >= 0; i--) {
  17.     // An ArrayList doesn't know what it is storing,
  18.     // so we have to cast the object coming out.
  19.     Ball ball = (Ball) balls.get(i);
  20.     ball.move();
  21.     ball.display();
  22.     if (ball.finished()) {
  23.       // Items can be deleted with remove().
  24.       balls.remove(i);
  25.     }
  26.   }  
  27. }

  28. void mousePressed() {
  29.   // A new ball object is added to the ArrayList, by default to the end.
  30.   balls.add(new Ball(mouseX, mouseY, ballWidth));
  31. }
复制代码


HashMap(基于哈希表的Map数据结构
描述:基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。 此实现假定哈希函数将元素适当地分布在各桶之间,可为基本操作(get 和 put)提供稳定的性能。迭代 collection 视图所需的时间与 HashMap 实例的“容量”(桶的数量)及其大小(键-值映射关系数)成比例。所以,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)。
语法:

HashMap()HashMap(initialCapacity)HashMap(initialCapacity, loadFactor)HashMap(m)
例子:
  1. import java.util.Iterator;
  2. import java.util.Map;

  3. HashMap hm = new HashMap();

  4. hm.put("Ava", 1);
  5. hm.put("Cait", 35);
  6. hm.put("Casey", 36);

  7. Iterator i = hm.entrySet().iterator();  // Get an iterator

  8. while (i.hasNext()) {
  9.   Map.Entry me = (Map.Entry)i.next();
  10.   print(me.getKey() + " is ");
  11.   println(me.getValue());
  12. }
复制代码


Object(对象):
描述:对象是类的实例。对象object是一些相关的变量和方法的软件集。软件对象经常用于模仿现实世界中我们身边的一些对象。对象是理解面向对象技术的关键。你在学习之前可以看看现实生活中的对象,比如狗、桌子、电视、自行车等等。你可以发现现实世界中的对象有两个共同特征:它们都有状态和行为。比如狗有自己的状态(比如名字、颜色、生育以及饥饿等等)和行为(比如摇尾巴等等)。同样自行车也有自己的状态(比如当前档位、两个轮子等等)和行为(比如刹车、加速、减速以及改变档位等等)
语法:
ClassName instanceName
例子:
  1. // Declare and construct two objects (h1, h2) from the class HLine
  2. HLine h1 = new HLine(20, 2.0);
  3. HLine h2 = new HLine(50, 2.5);

  4. void setup()
  5. {
  6.   size(200, 200);
  7.   frameRate(30);
  8. }

  9. void draw() {
  10.   background(204);
  11.   h1.update();
  12.   h2.update();  
  13. }

  14. class HLine {
  15.   float ypos, speed;
  16.   HLine (float y, float s) {  
  17.     ypos = y;
  18.     speed = s;
  19.   }
  20.   void update() {
  21.     ypos += speed;
  22.     if (ypos > width) {
  23.       ypos = 0;
  24.     }
  25.     line(0, ypos, width, ypos);
  26.   }
  27. }
复制代码

String(字符串数据结构):
描述:一个字符串是一个字符序列。类字符串包括方法检查单个字符,比较字符串,搜索字符串,提取字符串的一部分,整个字符串转换大写和小写。字符串总是定义里面的双引号(“ABC”),字符总是定义在单引号('A')。 要比较两个字符串的内容,使用等于()方法,如“如果(那么a.Equals (二))“,而不是”如果(==)“。一个String对象,因此比较他们只用==操作符比较两个字符串是否存储在相同的内存位置。使用的equals()方法将确保的实际内容进行比较。(参考故障排除有更详细的解释)。因为引号之间定义一个String,String本身内包括标记,你必须使用\(反斜杠)字符。(见上面的第三个例子。)这就是所谓的转义序列。其他的转义序列包括\ t表示制表符的\ n新线。因为反斜杠是转义字符,在字符串包括一个单反斜线,你必须使用两个连续的反斜杠,如:\ \ 有多个字符串方法比自本网页链接。位于其他文档在网上官方Java文档。
语法:
String(data)String(data, offset, length)
例子:
  1. String str1 = "CCCP";
  2. char data[] = {'C', 'C', 'C', 'P'};
  3. String str2 = new String(data);
  4. println(str1);  // Prints "CCCP" to the console
  5. println(str2);  // Prints "CCCP" to the console
  6. // Comparing String objects, see reference below.
  7. String p = "potato";
  8. if (p == "potato") {
  9.   println("p == potato, yep.");  // This will not print
  10. }
  11. // The correct way to compare two Strings
  12. if (p.equals("potato")) {
  13.   println("Yes, the contents of p and potato are the same.");
  14. }
  15. // Use a backslash to include quotes in a String
  16. String quoted = "This one has "quotes"";
  17. println(quoted);  // This one has "quotes"
复制代码

方法:
charAt()        返回指定索引处的字符
equals()        到指定的对象比较字符串
indexOf()        返回在输入串中第一次出现的字符的索引值
length()        返回输入字符串中的字符数
substring()        返回一个新字符串输入字符串的一部分
toLowerCase()        所有字符转换为大写
toUpperCase()        所有字符转换为小写

Table(表):
描述:提供按行和列组织的基于网格的表示形式的块级别流内容元素。
语法:Table a;
例子:
  1. // A Bubble class

  2. class Bubble {
  3.   float x,y;
  4.   float diameter;
  5.   String name;
  6.   
  7.   boolean over = false;
  8.   
  9.   // Create  the Bubble
  10.   Bubble(float x_, float y_, float diameter_, String s) {
  11.     x = x_;
  12.     y = y_;
  13.     diameter = diameter_;
  14.     name = s;
  15.   }
  16.   
  17.   // CHecking if mouse is over the Bubble
  18.   void rollover(float px, float py) {
  19.     float d = dist(px,py,x,y);
  20.     if (d < diameter/2) {
  21.       over = true;
  22.     } else {
  23.       over = false;
  24.     }
  25.   }
  26.   
  27.   // Display the Bubble
  28.   void display() {
  29.     stroke(0);
  30.     strokeWeight(2);
  31.     noFill();
  32.     ellipse(x,y,diameter,diameter);
  33.     if (over) {
  34.       fill(0);
  35.       textAlign(CENTER);
  36.       text(name,x,y+diameter/2+20);
  37.     }
  38.   }
  39. }
  40. /**
  41. * Loading Tabular Data
  42. * by Daniel Shiffman.  
  43. *
  44. * This example demonstrates how to use loadTable()
  45. * to retrieve data from a CSV file and make objects
  46. * from that data.
  47. *
  48. * Here is what the CSV looks like:
  49. *
  50.    x,y,diameter,name
  51.    160,103,43.19838,Happy
  52.    372,137,52.42526,Sad
  53.    273,235,61.14072,Joyous
  54.    121,179,44.758068,Melancholy
  55. */

  56. // An Array of Bubble objects
  57. Bubble[] bubbles;
  58. // A Table object
  59. Table table;

  60. void setup() {
  61.   size(640, 360);
  62.   loadData();
  63. }

  64. void draw() {
  65.   background(255);
  66.   // Display all bubbles
  67.   for (Bubble b : bubbles) {
  68.     b.display();
  69.     b.rollover(mouseX, mouseY);
  70.   }

  71.   textAlign(LEFT);
  72.   fill(0);
  73.   text("Click to add bubbles.", 10, height-10);
  74. }

  75. void loadData() {
  76.   // Load CSV file into a Table object
  77.   // "header" option indicates the file has a header row
  78.   table = loadTable("data.csv","header");

  79.   // The size of the array of Bubble objects is determined by the total number of rows in the CSV
  80.   bubbles = new Bubble[table.getRowCount()];

  81.   // You can access iterate over all the rows in a table
  82.   int rowCount = 0;
  83.   for (TableRow row : table.rows()) {
  84.     // You can access the fields via their column name (or index)
  85.     float x = row.getFloat("x");
  86.     float y = row.getFloat("y");
  87.     float d = row.getFloat("diameter");
  88.     String n = row.getString("name");
  89.     // Make a Bubble object out of the data read
  90.     bubbles[rowCount] = new Bubble(x, y, d, n);
  91.     rowCount++;
  92.   }  

  93. }

  94. void mousePressed() {
  95.   // Create a new row
  96.   TableRow row = table.addRow();
  97.   // Set the values of that row
  98.   row.setFloat("x", mouseX);
  99.   row.setFloat("y", mouseY);
  100.   row.setFloat("diameter", random(40, 80));
  101.   row.setString("name", "Blah");

  102.   // Writing the CSV back to the same file
  103.   saveTable(table,"data/data.csv");
  104.   // And reloading it
  105.   loadData();
  106. }
复制代码

XML(可扩展标记语言数据类型):
描述:可扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。 XML是标准通用标记语言 (SGML) 的子集,非常适合 Web 传输。XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。

XML
是一种表示XML对象,能够解析XML代码。使用loadXML的()来加载外部XML文件和创建XML对象。 只有文件编码为UTF-8(或纯ASCII)被正确解析XML文件里面的编码参数被忽略。
语法:
XML xml;
例子:
  1.         
  2. // The following short XML file called "mammals.xml" is parsed
  3. // in the code below. It must be in the project's "data" folder.
  4. //
  5. // <?xml version="1.0"?>
  6. // <mammals>
  7. //   <animal id="0" species="Capra hircus">Goat</animal>
  8. //   <animal id="1" species="Panthera pardus">Leopard</animal>
  9. //   <animal id="2" species="Equus zebra">Zebra</animal>
  10. // </mammals>

  11. XML xml;

  12. void setup() {
  13.   xml = loadXML("mammals.xml");
  14.   XML[] children = xml.getChildren("animal");

  15.   for (int i = 0; i < children.length; i++) {
  16.     int id = children[i].getInt("id");
  17.     String coloring = children[i].getString("species");
  18.     String name = children[i].getContent();
  19.     println(id + ", " + coloring + ", " + name);
  20.   }
  21. }

  22. // Sketch prints:
  23. // 0, Capra hircus, Goat
  24. // 1, Panthera pardus, Leopard
  25. // 2, Equus zebra, Zebra
复制代码

方法:
getParent()        获取元素的父元素的副本
getName()        获取元素的全名
setName()        设置元素的名称
hasChildren()        检查不是一个元素是否有任何孩子
listChildren()        返回一个数组的所有孩子的名字
getChildren()        返回一个数组,包含所有子元素
getChild()        返回的子元素指定的索引值或路径
addChild()        追加一个新的子元素
removeChild()        删除指定的子
getAttributeCount()        计算指定元素的属性
listAttributes()        作为一个数组返回一个列表的所有属性的名称
hasAttribute()        检查不是一个元素是否有指定的属性
getString()        获取元素的内容作为一个字符串
setString()        设置元素的内容作为一个字符串
getInt()        获取元素的内容为一个int
setInt()        元素的内容设置为一个int
getFloat()        获取为float元素的内容
setFloat()        设置为float元素的内容
getContent()        获取元素的内容
setContent()        设置一个元素的内容
format()        格式的XML数据作为一个String
toString()        作为一个字符串使用默认格式获取XML数据
估计看到这里,同学们头都大了,没关系,本节课主要要求掌握基本数据类型,
了解数据结构。关于详细的数据结构的使用我们后续课程还是会讲到的。不要太着急。
那么,下课!{:soso__13766225770624999893_3:}

回复

使用道具 举报

 楼主| 发表于 2013-5-8 09:44:11 | 显示全部楼层
看类没图,不火啊~哈哈
数据结构可是程序的基础。
回复 支持 反对

使用道具 举报

发表于 2013-5-8 13:55:21 | 显示全部楼层
我来帮忙点把火
回复 支持 反对

使用道具 举报

发表于 2013-5-8 16:23:07 | 显示全部楼层
{:soso__10594509353080808576_5:}
更新的好快啊!
回复 支持 反对

使用道具 举报

发表于 2013-5-20 13:29:16 | 显示全部楼层
初步了解了各种变量,做个记号,回头再查
回复 支持 反对

使用道具 举报

发表于 2013-6-24 20:37:18 | 显示全部楼层
问个问题,为什么代码的前面都写着是ARDUINO 代码?
这些代码是通用的吗?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2013-6-28 20:26:06 | 显示全部楼层
高粱 发表于 2013-6-24 20:37
问个问题,为什么代码的前面都写着是ARDUINO 代码?
这些代码是通用的吗?

本站不支持Processing的语法高亮。。。。所以用的Arduino的语法高亮。谢谢支持。
回复 支持 反对

使用道具 举报

发表于 2013-7-1 00:15:17 | 显示全部楼层
呵呵,挺好的,既然讲课总要从头开始,学生需要具备哪些基础建议说明,对了还有课程的目标,毕竟是一趟旅行,目的地在哪?那的风景好么?
回复 支持 反对

使用道具 举报

发表于 2013-11-8 14:50:14 | 显示全部楼层
难得做了中文教程,感谢
回复 支持 反对

使用道具 举报

发表于 2014-12-6 18:30:39 | 显示全部楼层
前面看着还好,后面就云里雾里了哈哈.
回复 支持 反对

使用道具 举报

发表于 2017-5-31 13:27:32 | 显示全部楼层
color c3 = get(10, 50);  


这句话的意思是获取坐标(10,50)的颜色吗?
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-3-29 19:07 , Processed in 0.053314 second(s), 25 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表