读完本文你会了解:
- Java有关数组的基础知识
- 静态方法的深入理解-见参考
- 练习一下二分查找
Primitive types:
data type | representation |
---|---|
byte | 8-bit |
char | 16-bit |
short | 16-bit |
int | 32-bit |
float | 32-bit |
long | 64-bit |
声明语句:声明语句将一个变量名和一个类型在编译时关联起来。Java是一种强类型的语言,因为Java编译器会检查类型的一致性。
循环语句:
- break语句,立即从循环中退出
- continue语句,立即开始下一循环
Array
Definition:
An arroy stores a sequence of values that are all of the same type.if we have N
values,we can use the notation a[i]
to refer i
th value of i
from 0
to N-1
.
Making an array involves three distinct steps:
- Declare the array name and type
- Creat the array
- Initialize the array values
//颠倒数组的元素
int N = a.length;
for (int i=0; i < N/2; i++) {
double temp = a[i];
a[i] = a[N-1-i];
a[N-1-i] = temp;
}
//矩阵相乘
int N = a.length;
double[][] c = new double[N][N];
for (int i=0;i < N; i++)
for (int j=0; j < N; j++){
for (int k=0;k < N; k++)
c[i][j] += a[i][k]*a[k][j];
}
example:
double[] a; //declaration
a = new double[N]; //creation
for(int i = 0; i<N ; i++) //initialization
a[i] = 0.0;
-
Using:
Java does automatic bounds checking-if you access an array with an illegal index your program will terminate with anArrayIndexOutOfBoundsException
-
Alising(混淆):
An array name refers to the whole array-if wo assign one array name to another,then both refer to the same array,as illustrate in the following code fragment.
int [] a = new int[N];
...
a[i] = 1234;
...
int [] b = a;
...
b[i] = 5678; //a[i] = 5678.
Static method
-
Defining a static method:
A method encapsulates a computation that is defined as a statements. A method takes arguments and computes a return value of some data type or causes aside effect
. - Java method have features:
- Arguments are passd by value.
- Method names can be overloaded.
- A method has a signal return but may have multiple return statements.
- A method can have side effects.
Binary Search
public class BinarySearch{
public static int rank(int key, int[] a){
int lo = 0;
int hi = a.length - 1;
while(lo <= hi){
int mid = lo + (hi - lo)/2;
if (key < mid) hi = mid - 1;
if (key > mid) lo = mid + 1;
else return mid;
}
return -1;
}
public static void main(String[] args){
In in = new In(args[0]);
int[] whitelist = in.readInts();
Array.sort(whitelist);
while(!in.isEmpty()){
int key = in.readInt();
if (rank(key, whitelist) < 0)
StdOut.println(key)
}
}
}
Web Exercises
1 Wget. Write a program Wget.java
that reads in data from the URL specifiedon the command line and saves it in a file with the same name.
public static void main(String[] args)
{
String URL = args[0];
In in = new In(URL);
String data = Sed.readAll();
String filename = URL.substring(URL.lastIndexOf('/')+1);
Out out = new Out(filename);
out.println(data);
out.close;
}
2 编写一段代码,将一个正整数N用二进制表示并转换为一个String
类型的值s。
String s = "";
for(int n = N;n > 0;n++)
s = (n % 2) + s;
3 Right triangle.Write a client RightTriangle.java that draws a right triangle and a circumscribing circle.
参考
static method: