要求:
定义一个类实现学生基本信息的概念,包括的变量有“姓名”“成绩”,包括的方法有输入姓名或学号,“查询”学生成绩。
思路:
大体思路:①存储–>②查询
①存储:以数组形式,三个数组,一个存名字,一个存学号,一个存分数。
关键:根据数组下标变量可以确定一个人的数据
②所以查询的时候,无论是查找名字还是学号,只要确定数组下标变量就能找到同一个人的其它数据。
代码
import java.util.Scanner; class Student{ String name[] = {"小明","小红"}; String id[] = {"1","2"}; int score[] = {92,95}; int checkScore(String student_name_id) { for(int i=0; i<2; i++) { if( student_name_id.equals(name[i]) ) { return score[i]; } } for(int j=0; j<2; j++) { if( student_name_id.equals(id[j]) ) { return score[j]; } } return 404; } } public class Example4{ public static void main(String args[]) { Student student1; student1 = new Student(); System.out.println("请输入名字或者学号查询成绩:"); Scanner x = new Scanner(System.in); String input_name = x.nextLine(); int student_score = student1.checkScore(input_name); if(student_score != 404) { System.out.println("您的成绩为:"+student_score); } else { System.out.println("查不到此同学的成绩!"); } } }