数组
- 有一个数列:8,4,2,1,23,344,12
猜数游戏:从键盘中任意输入一个数据,判断数列中是否包含此数
int[] array={8,4,2,23,344,12};
Scanner input = new Scanner(System.in);
int num =input.nextInt();
int i=0;
for ( i=0;i<array.length;i++){
if (array[i]==num){
System.out.println("包含");
break;
}
}
if (i==array.length) {
System.out.println("不包含");
}
- 从键盘输入本次Java考试五位学生的成绩,求考试成绩最高分
Scanner input = new Scanner(System.in);
int[] array=new int[5];
System.out.println("输入成绩");
for (int i=0;i<array.length;i++){
System.out.println("请输入第"+(i+1)+"次成绩");
array[i]=input.nextInt();
}
int max=0;
for (int i=0;i<array.length;i++){
if (max < array[i]){
max=array[i];
}
}
System.out.println(max);
- 有一组学员的成绩{99,85,82,63, 60},将它们按升序排列。要增加一个学员的成绩,将它插入成绩序列,并保持升序。
int []scores = {99,85,82,63,60};
Arrays.sort(scores);
for (int i = 0;i<scores.length;i++){
System.out.print(scores[i]+" ");
}
Scanner input = new Scanner(System.in);
System.out.println("输入下一个学生成绩");
int in=input.nextInt();
int pos = 0;
for (int i =0; i<scores.length;i++) {
if (in <= scores[i]) {
pos = i;
break;
}
}
int[] scores2= new int[6];
for (int i = 0;i<pos;i++){
scores2[i]=scores[i];
}
scores2[pos]=in;
for ( int i=pos+1;i<scores2.length;i++){
scores2[i]=scores[i-1];
}
for (int i = 0;i<scores2.length;i++){
System.out.println(scores2[i]+" ");
}
将 一组乱序的字符进行排序
进行升序和逆序输出
String[] zi ={"a","c","u","b","e","p","f","z"};
Arrays.sort(zi);
for (int i =0;i<zi.length;i++){
System.out.print(zi[i]);
}
System.out.println("倒序");
for (int i = zi.length-1;i>=0;i--){
System.out.print(zi[i]);
}
- 在上一个练习的基础上改进:
向上一个练习中得到的升序字符序列中插入一个新的字符,要求插入之后字符序列仍保持有序
String[] zimu = {"a", "c", "u", "b", "e", "p", "f", "z"};
for (int i = 0; i < zimu.length; i++) {
System.out.print(zimu[i]+" ");
}
Arrays.sort(zimu);
for (int i =0;i<zimu.length;i++){
System.out.print(zimu[i]+" ");
}
String m = "m";
int pos=6;
String[] zimu2=new String[9];
for (int i =0;i<pos;i++){
zimu2[i]=zimu[i];
}
zimu2[pos]=m;
for (int i =pos+1;i<zimu2.length;i++){
zimu2[i]=zimu[i-1];
System.out.println(zimu2[i]);
}
for (int i =0;i<zimu2.length;i++){
System.out.print(zimu2[i]+" ");
}