練習一:招聘啓事,需要IT人才,有意者請撥打電話
public class Test {
public static void main(String[] args) {
int[] arr = new int[] { 8, 2, 1, 0, 3 };
int[] index = new int[] { 2, 0, 3, 2, 4, 0, 1, 3, 2, 3, 3 };
String tel = "";
for (int i = 0; i < index.length; i++) {
tel += arr[index[i]];
}
System.out.println("聯繫方式:" + tel);
}
}
這題並不複雜,arr[index[i]]這裏是一個嵌套。根據index[i]的角標來尋找arr[]的角標。
練習二:
從鍵盤讀入學生成績,找出最高分,並輸出學生成績等級。
成績>=最高分-10 等級爲’A’
成績>=最高分-20 等級爲’B’
成績>=最高分-30 等級爲’C’
其餘 等級爲’D’
提示:先讀入學生人數,根據人數創建int數組,存放學生成績。
思路:我分爲五個步驟
1.使用Scanner,讀取學生個數
2.創建數組,存儲學生成績:動態初始化
3.給數組中的元素賦值
4.獲取數組中的元素的最大值:最高分
5.根據每個學生成績與最高分的差值,得到每個學生的等級,並輸出等級和成績
import java.util.Scanner;
public class ArrayDemo1 {
public static void main(String[] args) {
//1.使用Scanner,讀取學生個數
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入學生人數:");
int number = scanner.nextInt();
//2.創建數組,存儲學生成績:動態初始化
int[] scores = new int[number];
//3.給數組中的元素賦值
System.out.println("請輸入" + number + "個學生成績:");
int maxScore = 0;
for(int i = 0;i < scores.length;i++){
scores[i] = scanner.nextInt();
//4.獲取數組中的元素的最大值:最高分
if(maxScore < scores[i]){//這裏是在給每個元素賦值的同時就已經將最高分尋找出來了
maxScore = scores[i];
}
}
// for(int i = 0;i < scores.length;i++){//這裏沒有上面的方便,因爲這裏還比較了一次。
// if(maxScore < scores[i]){
// maxScore = scores[i];
// }
// }
//5.根據每個學生成績與最高分的差值,得到每個學生的等級,並輸出等級和成績
char level;
for(int i = 0;i < scores.length;i++){
if(maxScore - scores[i] <= 10){
level = 'A';
}else if(maxScore - scores[i] <= 20){
level = 'B';
}else if(maxScore - scores[i] <= 30){
level = 'C';
}else{
level = 'D';
}
System.out.println("同學" + i +
" 分數是 " + scores[i] + ",成績是" + level);
}
System.out.println("最高分爲" + maxScore);
}
}
遍歷了三遍數組