accp6.0JAVA1第九章上机练习
accp6.0JAVA1第九章上机练习
练习1:维护有序的图书列表
import java.util.Scanner;
/**
* 顺序插入图书
*/
public class Book {
public static void main(String[] args) {
String[] books = new String[]{"Computer","Hibernate","Java","Struts"};
String[] newBooks = new String[books.length+1]; //插入新书后的数组
String book = "";//保存用户输入的图书名称
int index = books.length; //保存新书插入位置
//输出插入前的结果
System.out.print("插入前的数组为:");
for(int i = 0; i < books.length ; i++){
System.out.print(books[i]+" ");
}
//将数组books中的元素复制到数组newBooks中
for(int i = 0; i < books.length; i++){
newBooks[i] = books[i];
}
//输入新书名称
Scanner input = new Scanner(System.in);
System.out.print("\n请输入新书名称:");
book = input.nextLine();
//找到新元素的插入位置
for(int i = 0; i < books.length; i++){
if(books[i].compareToIgnoreCase(book) > 0){
index = i;
break;
}
}
for(int i = newBooks.length-1; i > index; i--){
newBooks[i] = newBooks[i-1]; //index下标开始的元素后移一个位置
}
newBooks[index] = book; //新元素放在index的位置
//输出插入后的结果
System.out.print("插入后的数组为:");
for(int i = 0; i < newBooks.length; i++){
System.out.print(newBooks[i]+" ");
}
}
}
练习2:计算一个班级的成绩平均分
import java.util.Scanner;
/**
* 计算一个班的平均分
*/
public class AvgScore {
public static void main(String args[]){
int[] score = new int[4];//成绩数组
float sum = 0.0f;//成绩总和
float average = 0.0f;//成绩平均值
//循环输入学员成绩
Scanner input = new Scanner(System.in);
System.out.println("请输入4位学员的成绩");
for(int i = 0; i < score.length; i++){
System.out.print("第"+ (i+1) +"位学员的成绩:");
score[i] = input.nextInt();
sum = sum + score[i]; //成绩累加
}
average = sum / score.length;//计算平均值
System.out.println("参赛学员的平均分是:" + average);
}
}
练习3:输入行数,打印直角三角形
import java.util.Scanner;
/**
* 输入行数打印直角三角形
*/
public class RTriAngle {
public static void main(String[] args) {
int rows = 0;//三角形行数
System.out.print("请输入直角三角形的行数:");
Scanner input = new Scanner(System.in);
rows = input.nextInt();
//打印直角三角形
for(int i = 1; i <= rows