一、顺序搜索
下面的程序在一个数组中找100,如果找到了则返回下标,如果没找到则返回-1.
/**
This program sequentially searches an
int array for a specified value.
*/
public class SearchArray
{
public static void main(String[] args)
{
int[] tests = { 87, 75, 98, 100, 82 };
int results;
// Search the array for the value 100.
results = sequentialSearch(tests, 100);
// Determine whether 100 was found and
// display an appropriate message.
if (results == −1)
{
System.out.println("You did not " +
"earn 100 on any test.");
}
else
{
System.out.println("You earned 100 " +
"on test " + (results + 1));
}
}
/**
The sequentialSearch method searches an array for
a value.
@param array The array to search.
@param value The value to search for.
@return The subscript of the value if found in the
array, otherwise −1.
*/
public static int sequentialSearch(int[] array,
int value)
{
int index; // Loop control variable
int element; // Element the value is found at
boolean found; // Flag indicating search results
// Element 0 is the starting point of the search.
index = 0;
// Store the default values element and found.
element = −1;
found = false;
// Search the array.
while (!found && index < array.length)
{
if (array[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}
ps:如果想保存静态方法里的return值,可以将方法值赋值给方法外的一个变量
二、二维数组
二维数组实际上就是数组的数组,但是我们可以具象化地理解为它由行和列组成
1、二维数组的声明
要声明一个二维数组,需要两个括号和两个大小的标记符,eg:
double[][] scores = new double[3][4];
double后面两个括号就表明这个scores变量是一个二维数组类型的变量
注意第一个括号内的是行的大小,第二个括号内是列的大小
下面的图片展示了二维数组中每一个元素的下标序号:比如[x][y]表示第x+1行第y+1列 ,注意这和表示坐标位置的数对是相反的(数对中(2,3)表示第3行第2列)
2、二维数组的初始化
在初始化二维数组时,java将每一行的数组封装在其自己的一组大括号中:
int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
更直观的写法:
int[][] numbers = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
第一行的数据实际上就是一个一维数组,但是在这里不需要再使用关键字new去创建这个一维数组了,java已经自动创建好了,如下图:
3、二维数组的“length field”
二维数组的行和列都有对应的length field,在理解这一点的时候,将二维数组看作是数组的数组会更为容易。
numbers变量引用一个具有三个变量的一维数组元素。这三个元素中的每一个都是对另一个一维数组的引用。数组中的元素numbers[0]引用的数组中的元素是numbers[0][0]、numbers[0][1]和numbers[0][2]。
下面这个程序展示了如何使用二维数组的length field
/**
This program uses the length fields of a 2D array
to display the number of rows, and the number of
columns in each row.
*/
public class Lengths
{
public static void main(String[] args)
{
// Declare a 2D array with 3 rows
// and 4 columns.
int[][] numbers = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
// Display the number of rows.
System.out.println("The number