Java array indexing problems

/ *
Two minor problems common array operations:
ArrayIndexOutOfBoundsException: Array index out of bounds abnormal
reasons: you visit the index does not exist.

NullPointerException: null pointer abnormal
reasons: no longer pointing to an array of heap memory. And you also use to access the elements of an array name.

Role: the problem all at your own Exception ending scenes sum up. After the encounter on record.
Phenomenon, causes, solutions.
* /
Class ArrayDemo6 {
public static void main (String [] args) {
// definition array
int [] = {l, 2,3} ARR;

//System.out.println(arr[3]);

// reference types of constants: constant air null
ARR = null;
System.out.println (ARR [0]);
}
}
two common minor problems with arrays:
the array is checked several times in a number of occurrences.
Demand: Finding array element (index to find the first occurrence of the specified element in the array)

analysis:
A: define an array, and static initialization.
B: Write a function realization
iterate sequentially retrieve each element in the array, and comparing the known data and
if they are equal, the current index value is returned.
* /
Class ArrayTest5 {
public static void main (String [] args) {
// definition of an array, and the static initialization
int [] = {200,250,38,888,444 ARR};

// requirements: I want to find in the first array 250 occurrences of index
int index = getIndex (ARR, 250);
System.out.println ( "250 in the index array is the first time:" + index);

int index2 = getIndex2 (ARR, 250);
the System. out.println ( "the index in the array 250 first appears is:" + index2);

int = Index3 getIndex2 (ARR, 2500);
System.out.println ( "the index in the array 2500 is the first occurrence : "+ Index3);
}

/ *
demand: Find the index data in the specified array first occurrence of
two distinct:
return value type: int
parameter list: int [] ARR, int value
* /
public static int getIndex (int [] ARR, int value) {
// iterate sequentially obtain each element of the array, and comparing the known data
for (int x = 0; x <arr.length; x ++) {
IF (ARR [X] == value) {
// if equal, returns the current index value.
the X-return;
}
}

// The current code has a small problem
// data is, if I'm looking for does not exist in the array, it can not find, can not find, you can do the corresponding return?
// therefore error .

// as long as the judge, it could be false, so we have to be careful.


// If no data, we can generally return a negative number, and return -1
return -1;
}

public static int getIndex2 (int [] ARR, int value) {
// define an index
int index = -1 ;

// index have to modify the value
for (int X = 0; X <arr.length; X ++) {
IF (ARR [X] == value) {
index = X;
BREAK;
}
}

// returns the index
return index;
}
}

Guess you like

Origin www.cnblogs.com/lszbk/p/12318597.html