这一节课主要是学习数组,包括一维数组、二维数组和三维数组,主要是一维数组的学习。数组是用来存储一个元素个数固定且元素类型相同的有序集。数组的声明使用语法:
elementType[] arrayRefVar。不同于基本数据类型变量的声明,声明一个数组变量时并不在内存中给数组分配任何空间,它只是创建一个对数组的引用的存储位置。一个数组创建之后就不能再修改它的大小,arrayRefVar.length可以求得数组的大小。数组元素可以通过下标访问,其范围从0开始到arrayRefVar.length-1;所以很多关于数组的运用,都是基于该下标的运用,这里就涉及到了一个很关键的技术就是循环,因为数组大小固定,所以一般都是使用for循环来处理数组的各种问题。Java支持一个简便的for循环,称之为for-each循环,可以顺序遍历整个数组。代码如下:
for (double u:mylist){
System.out.println(u);
}
数组的复制有三种方法:1、使用循环语句逐个地复制数组的元素;2/使用System类中的静态方法arraycopy;
System.arraycopy(sourceArray,0,targetArry,0,sourceArray.length);
数组的另一个重要技术就是给方法传递数组,它传递的是对方法的引用。如果改变方法中的数组,方法外的数组也变化了。在方法中可以把类型相同但个数可变的参数传递给方法。
typeName...parameterName(类型名。。。参数名)
二维数组实际上是一个数组,它的每个元素都是一个一维数组。它的处理方法和一维数组差不多都是利用循环来解决问题,只不过它是用二重循环来解决。
在这一节中我遇到的一个难题就是编写一个程序,读入10个数并且显示互不相同的数(即一个数出现多次,但仅显示一次)。大体解法就是如果读入的数是一个新数,则将它存储在数组中,如果该数在数组中,则忽略它。刚开始就是不会数组的遍历,所以花费了不少时间。
以下是这节的相关一道习题:
编写一个程序,读入学生成绩,获取最高分,并划分等级。
package best;
import java.util.Scanner;
public class Best {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int num = in.nextInt();
System.out.println("Enter "+num+" score: ");
int[] scores = new int[num];
int i;
for( i = 0;i<scores.length;i++){
scores[i]=in.nextInt();
}
int max = scores[0];
for(i=1;i<scores.length;i++){
if(scores[i]>max){
max = scores[i];
}
}
for(i=0;i<scores.length;i++){
if(scores[i]>=max-10){
System.out.println("Student "+i+" score is "+scores[i]+ " and grade is A");
}
else if(scores[i]>=max-20){
System.out.println("Student "+i+" score is "+scores[i]+ " and grade is B");
}
else if(scores[i]>=max-30){
System.out.println("Student "+i+" score is "+scores[i]+ " and grade is C");
}
else if(scores[i]>=max-40){
System.out.println("Student "+i+" score is "+scores[i]+ " and grade is D");
}
else{
System.out.println("Student "+i+" score is "+scores[i]+ " and grade is B");
}
}
}
}