数组与对象编程入门
立即解锁
发布时间: 2025-08-19 02:24:00 订阅数: 5 

### 数组与对象编程入门
在编程的世界里,数组和对象是非常重要的概念。下面将详细介绍数组的操作以及对象的创建和使用。
#### 数组的基本操作与线性搜索
数组是一种固定数量、相同类型元素按特定顺序排列的数据结构。数组中的每个项被称为元素,我们可以使用特定值来声明和初始化数组,通过索引(也称为下标)来引用数组元素,且数组索引从 0 开始。
例如,我们可以创建一个字符串数组,使用 `printArray()` 函数查看其内容:
```
[0] "George"
[1] "John"
[2] "Tom"
```
数组的一个常见操作是搜索特定值,其中线性搜索是一种简单但效率较低的方法。下面是实现线性搜索的具体步骤:
1. **创建新程序**:选择“文件”>“新建”,将程序保存为 `LinearSearch`。
2. **定义数组和搜索值**:
```java
int[] temperatures = {57, 10, 32, 78, 212, 101};
int seeking = 78;
println("Searching for: " + seeking);
```
3. **使用 `for` 循环遍历数组**:
```java
for (int count = 0; count < temperatures.length; count = count + 1) {
println("temperatures[" + count + "] = " + temperatures[count] );
}
```
4. **检查当前元素是否为搜索值**:
```java
for (int count = 0; count < temperatures.length; count = count + 1) {
println("temperatures[" + count + "] = " + temperatures[count] );
if (temperatures[count] == seeking) {
println(seeking + " has been found at [" + count + "]");
}
}
```
5. **显示搜索结束信息**:
```java
println("end of search");
```
如果希望用户能够指定要搜索的温度,可以修改程序如下:
```java
import static javax.swing.JOptionPane.*;
int[] temperatures = {57, 10, 32, 78, 212, 101};
String input;
input = showInputDialog("Enter temperature for search:");
int seeking;
seeking = int(input);
println("Searching for: " + seeking);
for (int count = 0; count < temperatures.length; count = count + 1) {
println("temperatures[" + count + "] = " + temperatures[count] );
if (temperatures[count] == seeking) {
println(seeking + " has been found at [" + count + "]");
}
}
println("end of search");
```
#### 数组的相关特性总结
- 数组变量存储的是数组在计算机内存中的地址。
- 使用大于或等于数组长度的索引会导致越界异常。
- 计数循环(尤其是 `for` 循环)对于处理数组非常有用。
- 数组是一种对象,其 `length` 属性存储了数组的长度。
- 提供了一些可用于数组的函数,如 `printArray()`、`min()` 和 `max()` 等,还提供了排序和复制数组的函数,数组也可以作为参数传递给函数。
#### 数组操作练习
以下是一些关于数组操作的练习,你可以尝试完成:
1. 编写程序:
- 声明一个可容纳 7 个 `int` 值的数组。
- 在控制台显示默认元素。
2. 编写程序:
- 声明一个可容纳 15 个 `float` 值的数组。
- 在控制台显示默认元素。
3. 创建一个数组来存储 5 个元音字符,并在控制台显示这些元素,输出格式如下:
```
[0] 'a'
```
0
0
复制全文
相关推荐










