数组练习题
import java.util.Scanner;
public class szlianxi1 {
public static void main(String[] args) {
// 1.读取学生个数
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生人数:");
int number = scanner.nextInt();
// 2.创建数组存储学生成绩,动态初始化
int[] scores = new int[number];
// 3.给数组中的元素赋值
int max = 0;
System.out.println("请输入" + number + "个学生成绩");
for (int i = 0; i < scores.length; i++) {
scores[i] = scanner.nextInt();
/*if (max < scores[i]) {
max = scores[i];可以先在此处求出最大值
}*/
}
// 4.获取数组中的最大值
for (int n = 0; n < scores.length; n++) {
if (max < scores[n]) {
max = scores[n];
}
}
// 5.根据成绩输出成绩并且判定等级
char level;
for (int d = 0; d < scores.length; d++) {
if (max - scores[d] <= 10) {
level = 'A';
} else if (max - scores[d] <= 20) {
level = 'B';
} else if (max - scores[d] <= 30) {
level = 'C';
} else {
level = 'E';
}
System.out.println("student "+d+"score is "+" "+scores[d]+"grade is"+level);
}
}
}
练习题2 杨辉三角
public class szlianxi2 {
public static void main(String[] args) {
int[][] arr=new int[][]{{3,5,8},{12,9},{7,0,6,4}};
int sum = 0;
for(int i = 0;i<arr.length;i++){
for(int j = 0;j<arr[i].length;j++){
sum+=arr[i][j];
}
}
System.out.println(sum);
// 杨辉三角
//1.声明一个二维数组
int[][] yanghui=new int[10][];
//2.赋值
for(int i=0;i<yanghui.length;i++){
yanghui[i]=new int[i+1];
//2.1给首末元素赋值
yanghui[i][0]=yanghui[i][i]=1;
//2.2给每行的非首末元素赋值
if(i>1){
for(int j=1;j<yanghui[i].length-1;j++){
yanghui[i][j]=yanghui[i-1][j-1]+yanghui[i-1][j];
}
}
}
//3.遍历
for(int i=0;i<yanghui.length;i++){
for(int j=0;j<yanghui[i].length;j++){
System.out.print(yanghui[i][j]+" ");
}
System.out.println();
}
}
}