public static void main(String[] args) {
*//**
* 字符串转为数组
*//*
String str = "helloworld";
char[] data = str.toCharArray();//将字符串转为数组
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
data[i] -= 32;
System.out.print(data[i] + " ");
}
System.out.println(new String(data));
}
运行结果截图
public static void outPut(int[] array){
if(array != null){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
int[] array = new int[5];
//填充数组
Arrays.fill(array,5);
System.out.println("填充数组:Arrays.fill(array,5)");
Test.outPut(array);
//将数组的第二第三元素赋值为8
Arrays.fill(array,2,4,8);
System.out.println("//将数组的第二第三元素赋值为8 Arrays.fill(array,2,4,8)");
Test.outPut(array);
int[] array1 = {7,8,3,2,12,6,3,5,4};
//对数组的2~6个进行排序
Arrays.sort(array1,2,7);
System.out.println("对数组的2~6个进行排序 Arrays.sort(array1,2,7)");
Test.outPut(array1);
//对整个数组进行排序
Arrays.sort(array1);
System.out.println("//对整个array1数组进行排序");
Test.outPut(array1);
//比较数组元素是否相等
System.out.println("比较数组元素是否相等" + Arrays.equals(array, array1));
int[] array2 = array1.clone();
System.out.println("比较数组克隆后元素是否相等" + Arrays.equals(array1, array2));
//二分法查找指定元素的下标(必须是排好序的)
Arrays.sort(array1);
System.out.println("元素3在array1中的位置" + Arrays.binarySearch(array1, 3));
//如果不存在就返回负数
System.out.println("元素9在array1中的位置" + Arrays.binarySearch(array1, 9));
}
结果截图

public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
arr = Arrays.copyOf(arr,arr.length + 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
结果
private static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
char[] chs = generate();
System.out.println(chs);
int count = 0;//猜错的次数
while (true) {
System.out.println("来 ~ 猜");
String str = scan.next().toUpperCase();
if(str.equals("EXIT")){
System.out.println("下次再见");
break;
}
char[] input = str.toCharArray();//字符串转数组
int[] result = check(chs,input);
if(result[0] == chs.length){
int score = 100 * chs.length - 10 * count;
System.out.println("猜对了,分数是" + score);
break;
}else{
count++;
System.out.println("对的个数为" + result[1] + ",位置对个数为" + result[0]);
}
}
}
//生成随机字符数组
public static char[] generate(){
char[] chs = new char[5];
char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'};
boolean[] flags = new boolean[letters.length];
for (int i = 0; i < chs.length; i++) {
int index;
do{
index = (int) (Math.random() * letters.length);
}while(flags[index] == true);
chs[i] = letters[index];
flags[index] = true;
}
return chs;
}
//对比:随机字符数组chs与用户输入废人字符数组input
public static int[] check(char[] chs,char[] input){
int[] result = new int[2];//(0,0)
for (int i = 0; i < chs.length; i++) {
for (int j = 0; j < input.length; j++) {
if(chs[i] == input[j]){
result[1]++;
if(i == j){
result[0]++;
}
break;
}
}
}
return result;
}
结果