数组
遍历数组
输入一个数字,从现有数组中查找是否存在
一般方法
package cn.edu.tyust.corejava.task;
import java.util.Scanner;
/**
*
* @author chenyanbing
* @version 1.0
*/
public class Sale {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int []date = {1,2,3,55,66,11,21,32,46};
int x = in.nextInt();
int loc = -1;
for(int i = 0; i < date.length; i++)
{
if(x == date[i])
{
loc = i;
break;
}
}
if(loc > -1)
{
System.out.println(x + "是第" + (loc + 1) + "位");
}
else
{
System.out.println("该数字不在其中");
}
}
}
for-each方法
for(<类型><变量>:<数组>){
…
}
package cn.edu.tyust.corejava.task;
import java.util.Scanner;
/**
*
* @author chenyanbing
* @version 1.0
*/
public class Sale {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int []date = {1,2,3,55,66,11,21,32,46};
int x = in.nextInt();
boolean found = false;
for(int i : date)
{
if (x == i)
{
found = true;
break;
}
}
if(found)
{
System.out.println(x + "在其中");
}
else
{
System.out.println(x + "不在其中");
}
}
}
遍历数组中的常见错误
- 循环结束条件是<=数组长度
- 离开循环后,继续用 i 做数组元素的下标
- 算法的思维不一定跟人一样
数组拷贝
Arrys.copyOf
/**
这样的两个数组虽然一样但是互不关联了
/
int []a = {1,2,3};
int []b = Arrays.copyOf(a, a.length);