当前位置:文档之家› 南昌大学Java实验报告

南昌大学Java实验报告

南昌大学实验报告学生姓名:学号:专业班级:实训类型:□验证□综合□设计□创新实验日期:2017.11.1 实验成绩:一、实验项目名称Java开发环境搭建和Java语言基础二、实验的评分标准实验分为A~F,A为最高,F最低。

F:在规定时间内没有完成所有的实验,而且没有及时提交实验报告,或者实验过程中出现了抄袭复制他人实验代码。

D:能完成实验,但是实验结果出现严重错误,不能体现对教学内容的理解。

C:能基本完成实验,实验结果基本正确。

但是实验内容有较少的错误,提交的实验代码质量一般。

B:能较好的完成实验,实验报告条理清楚,实验代码结构清晰,代码质量较高,及时更正试验中出现的错误,并对运行中一些异常错误进行分析,解释错误产生的原因。

A:能较好的完成实验,实验代码质量高,实验报告完成度高,能在实验完成的基础上,根据个人的理解增加实验的新功能,具有一定的创新能力。

三、实验目的和要求1.掌握Java的基础知识2.掌握和运用Java的控制语句和数组3.使用Eclipse平台开发Java应用四、实验内容1.HelloWorld的应用程序和Applet程序。

A.javap工具解析HelloWord字节码的类B.javap反汇编HelloWorld字节码C.修改代码,使之成为应用程序和Applet小程序两种程序的“入口”不同,一个是main()函数,一个是init()函数,所以直接添加代码即可,运行时,根据IDE的run功能,选择相应的程序执行即可。

第一个和最后一个分别是Applet程序和Application程序D.写文档注释,生成文件一些效果截图2.打印日历程序3.枚举类统计Java成绩非法输入程序会报错退出正确结果自学了一下javafx,写了个简陋的UI。

(要配合控制台输入数据,有待改进)4.四连子游戏继续自学了一下javafx,给这个游戏包装了一个UI。

本题和老师理解的要求可能有出入,游戏规则有点差别,但是底层逻辑是差不多的,于是我还是按照自己的想法写了下去,希望老师理解。

某一列下满,按钮失效获胜,信息提示绿色指示当前局该哪一方落子平局Restart:清盘重玩Quit:退出实验源代码如下:-------1.helloworld---------------package one;import java.applet.Applet;import java.awt.*;/*** This class is used to show hello world information* in two kinds of ways** 1.print the information in the console* 2.generate an applet to display the info** @author Yuchen Tian*/public class HelloWorld extends Applet{/*** main function for Application* @param args*/public static void main(String[] args){//for applicationSystem.out.println("Hello World!");}public void init(){ }//for applet/*** create an graph on applet to show info* @param g*/public void paint(Graphics g){g.drawString("Hello World!",20,20);}}------2.printCalendar-------------Part1---------------package two;/*this Month enum defines the 12 months of all yearincluding the information of:index:the order in current classname:the full name of the monthday:days in this month*/public enum Month {JAN(1,"January",30),FEB(2,"February",28),MAR(3,"March",31),APR(4,"April",30 ),MAY(5,"May",31),JUN(6,"June",30), JUL(7,"July",31),AUG(8,"August",31), SEP(9,"September",30),OCT(10,"October",31),NOV(11,"November",30),DEC(12,"De cember",31);private int index;private String name;private int day;Month(int index,String name,int day){this.index = index; = name;this.day = day;}public String getName(){return name;}public int getDay(){return day;}//when a month call this method,it becomes the month following itpublic Month next(){int index = (this.index+1 > 12) ? 1 : this.index+1;return getMonthByIndex(index);}//get a month according to the it's index in the enumpublic Month getMonthByIndex(int index){for(Month c:Month.values()){if(c.index == index)return c;}return null;}}-------part2-------package two;import java.util.Calendar;import java.util.GregorianCalendar;public class MyCalendar {private int year;private int startDay;private Month m;public MyCalendar(int year){this.year = year;this.startDay = getFirstDay(0,1) % 7;//month1,day1m = Month.JAN; //start month of the year}public int getFirstDay(int month, int day){GregorianCalendar tool = new GregorianCalendar(this.year,month,day); return tool.get(Calendar.DAY_OF_WEEK);//0 for Sun ,1 for Mon...}public void printMonth(Month m){//generate the head information of each monthSystem.out.printf("%20s\n",m.getName());System.out.println("--------------------");System.out.println("Su Mo Tu We Th Fr St");int count = 0;for(int i=0;i<startDay;++i){//print blanksSystem.out.printf("%3c",' ');count++;}for(int i=1;i<=getDays(m);++i){//print daysSystem.out.printf("%2d ",i);count++;if(count%7==0)System.out.println();}System.out.println();startDay = (getDays(m) + startDay) % 7; //change the startDay for the next month}public boolean isLeapYear(){return year%400 == 0 || (year%4 == 0 && year%100 !=0);}//get days in specific month//days in February is unique when it is leap year//hence,a special approach is implement to alter it rightpublic int getDays(Month m){int days = m.getDay();if(isLeapYear() && m.getName().equals(Month.FEB.getName()))//specialfor Februarydays += 1;return days;}//once printed the first month//change the m to the next monthpublic void printAllMonth(){for(int i = 0;i<12;++i){printMonth(m);m = m.next();}}}---------part3----------package two;import java.util.Scanner;public class PrintCalendar {public static void main(String[] args){//Prompt the user to input a yearScanner input = new Scanner(System.in);System.out.print("Please input a year:");int year = input.nextInt();//create a MyCalendar instanceMyCalendar cal = new MyCalendar(year);cal.printAllMonth();}}----------3,aggregate the scores----------------part1--------package three;public enum GradeRank {A("优秀",0),B("良好",1),C("中等",2),D("及格",3),E("不及格",4); private String info;private int index;GradeRank(String info, int index){ = info;this.index = index;}public int getIndex() {return index;}public String getInfo() {return info;}public GradeRank changeRank(Double grade){GradeRank g;if(grade>=90 && grade<=100)g = GradeRank.A;else if(grade<90 && grade>=80)g = GradeRank.B;else if(grade<80 && grade>=70)g = GradeRank.C;else if(grade<70 && grade>=60)g = GradeRank.D;else if(grade<60 && grade>=0)g = GradeRank.E;elseg = null;return g;}}-------part2-------package three;import java.util.Scanner;public class EvaluateGrade {private int[] collection;private GradeRank g; //the standard for Aggregatingprivate int num; //how many scores you need to calculatepublic EvaluateGrade(int num) {this.collection = new int[5];//n different ranksg = GradeRank.A;this.num = num;}//when a new score is input//g is gonna to change according to the value of the scorepublic void checkRank(Double grade){g = g.changeRank(grade);if(g==null){System.out.println("Invalid input!");System.exit(1);}collection[g.getIndex()]++;}public void countRank(){Scanner input = new Scanner(System.in);System.out.println("Input the scores:");for(int i = 0;i<num;i++){Double grade = input.nextDouble();checkRank(grade);}}public void display(){for(int i=0;i<5;i++)System.out.printf("%s%c%5.1f%c\n",indexToStr(i),':',getPercent(i),'%'); }//acquire the information using index//to display the outcome betterpublic String indexToStr(int i){for(GradeRank c : GradeRank.values()){if(c.getIndex()==i)return c.getInfo();}return null;}public double getPercent(int i){return ((double) collection[i]/num)*100;}}--------part3--------package three;import java.util.Scanner;public class Aggregate {public static void main(String[] args){Scanner number = new Scanner(System.in);System.out.print("Please input the number of scores you want to deal with:");int n = number.nextInt();EvaluateGrade checker = new EvaluateGrade(n);checker.countRank();checker.display();}}-----------4,chessgame----------------part1------/*this class is designed to store data in playing gamesand make the rule of the playing as well*/public class Game {private int[][] board;private int[] full;private boolean isBlack;public Game(){this.board = new int[7][];for(int i=0;i<7;i++)this.board[i] = new int[6];this.isBlack = true;//black side is firstfull = new int[7];for(int i=0;i<7;i++)full[i] = 5;}public boolean isBlack() {return isBlack;}//change to the other side to playpublic void inTurn(){this.isBlack = !this.isBlack;}public boolean isFull(int i){return full[i] == -1;}public boolean isAllFull(){for(int i=0;i<7;++i)if(!isFull(i))return false;return true;}//the most important part//check whether one side has won the gamepublic boolean checkWin(int i,int j){if(line(i,j)||column(i,j)||leftR(i,j)||rightL(i,j))return true;elsereturn false;}public boolean line(int i,int j){int cx = 0;for(int m =i+1;m<7 && board[m][j]==board[i][j];++m)cx++;for(int m = i-1;m>=0 && board[m][j]==board[i][j];--m)cx++;if(cx>=3)return true;elsereturn false;}public boolean column(int i,int j){int cx = 0;for(int n =j+1;n<6 && board[i][n]==board[i][j];++n)cx++;for(int n = j-1;n>=0 && board[i][n]==board[i][j];--n)cx++;if(cx>=3)return true;elsereturn false;}public boolean leftR(int i,int j){int cx = 0;for(int m=i+1,n=j+1;m<7 && n<6 && board[m][n]==board[i][j];++m,++n) cx++;for(int m=i-1,n=j-1;m>=0 && n>=0 && board[m][n]==board[i][j];--m,--n) cx++;if(cx>=3)return true;elsereturn false;}public boolean rightL(int i,int j){int cx = 0;for(int m=i-1,n=j+1;m>=0 && n<6 && board[m][n]==board[i][j];--m,++n) cx++;for(int m=i+1,n=j-1;m<7 && n>=0 && board[m][n]==board[i][j];++m,--n) cx++;if(cx>=3)return true;elsereturn false;}//change the data of game when one side drop the chesspublic int dropChess(int i){board[i][full[i]] = (isBlack()) ? 1 : 2;inTurn();full[i]--;return full[i]+1;}}-----part2------import javafx.geometry.Insets;import javafx.scene.control.Button;import javafx.scene.control.TextField;import yout.BorderPane;import yout.GridPane;import javafx.scene.paint.Color;import javafx.scene.shape.*;import javafx.scene.text.*;/*this class is designed to append graph of each element into the game determined the layout of these elements as wellmore importantly, the change of the elements as the game playing*/public class ChessBoard {private Game rule;//the elementsprivate Font font;private Rectangle[] recs;private TextField result;private Button[] bts;private Button[] indicator;private Button[] choice;private Circle[] light;private Circle[] chess;//the frameworkprivate GridPane board;private BorderPane frame;private GridPane control;//initialize all the elementsChessBoard() {this.rule = new Game();this.font = Font.font(null, FontWeight.NORMAL, null, 20);this.recs = new Rectangle[42];this.result = new TextField();this.bts = new Button[7];this.indicator = new Button[2];this.choice = new Button[2];this.light = new Circle[2];this.chess = new Circle[42];this.board = new GridPane();this.frame = new BorderPane();this.control = new GridPane();this.result = new TextField();}//set all the properties of the elementspublic void init() {for (int i = 0; i < 42; i++) {recs[i] = new Rectangle(60, 60);recs[i].setFill(Color.gray(0.36));chess[i] = new Circle(25);chess[i].setFill(Color.gray(0.36));}for (int i = 0; i < 7; i++) {bts[i] = new Button("Drop");bts[i].setPrefSize(60, 40);}for (int i = 0; i < 2; i++) {light[i] = new Circle(16);light[i].setFill(Color.rgb(0, 230, 0, 1));//control capacity }choice[0] = new Button("Restart");choice[1] = new Button("Quit");indicator[0] = new Button("Black");indicator[1] = new Button("White");for (int i = 0; i < 2; i++) {indicator[i].setFont(font);indicator[i].setPrefSize(100, 40);indicator[i].setMouseTransparent(true);choice[i].setPrefSize(150, 40);choice[i].setFont(font);}result.setFont(font);result.setPrefSize(180,50);result.setEditable(false);}//add all the elements into the main frame//set the layout between thempublic void load() {board.setHgap(1);control.setVgap(10);//fill the chess boardfor (int i = 0; i < 42; ++i){board.add(recs[i], i % 7, (i / 7) + 1);board.add(chess[i],i % 7, (i / 7) + 1);GridPane.setMargin(chess[i], new Insets(0, 0, 0, 5));}//for control partfor (int i = 0; i < 2; i++) {GridPane.setMargin(light[i], new Insets(0, 20, 0, 20)); GridPane.setMargin(choice[i], new Insets(20, 0, 0, 0)); control.add(choice[i], 0, i + 10, 2, 1);control.add(indicator[i], 0, i+1);control.add(light[i], 1, i+1);}control.add(result,0,3,2,1);GridPane.setMargin(result,new Insets(20, 20, 0, 0));for (int i = 0; i < 7; i++)board.add(bts[i], i, 0);frame.setCenter(board);frame.setRight(control);}public void clearBoard(){for(int i = 0;i<42;++i)chess[i].setFill(Color.gray(0.36));this.rule = new Game();result.clear();for(int i = 0;i<7;++i)getButton(i).setOpacity(1);}public int addChess(int i) {int pos = rule.dropChess(i);//(i,pos) is the right pointif (!rule.isBlack())chess[pos*7+i].setFill(Color.BLACK);elsechess[pos*7+i].setFill(Color.WHITE);return pos;}public void setBtsOff(int tag){if(tag<0){for(int i = 0;i<7;++i)getButton(i).setOpacity(0);}elsegetButton(tag).setOpacity(0);}public void changeLight() {if (rule.isBlack()) {light[0].setFill(Color.rgb(0, 230, 0, 1));light[1].setFill(Color.rgb(0, 230, 0, 0));} else {light[0].setFill(Color.rgb(0, 230, 0, 0));light[1].setFill(Color.rgb(0, 230, 0, 1));}}public boolean isWin(int i,int j){return rule.checkWin(i,j);}public BorderPane getFrame() {return frame;}public Button getButton(int i){return bts[i];}public boolean isFull(int i){return rule.isFull(i);}public Button getChoice(int i){return choice[i];}public void printInfo(int i,int j){if(isWin(i,j)) {if(rule.isBlack())result.setText("White side win!");elseresult.setText("Black side win!");}if(rule.isAllFull())result.setText("Draw!");}}-------part3-------import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import yout.GridPane;import javafx.stage.Stage;/*This class is designed to organize the changes of the game from the last lever logicallyWhat’s more,add events to certain circumstances, enabling the game run mo re fluently*/public class ControlGame extends Application {private ChessBoard chessBoard = new ChessBoard();private boolean lock = false;public void start(Stage stage){chessBoard.init();chessBoard.load();chessBoard.changeLight();addInfoEvents();addQuitEvent();addRestartEvent();Scene scene = new Scene(chessBoard.getFrame(),650,450);stage.setScene(scene);stage.show();}public void addInfoEvents(){for(int i = 0;i<7;++i){chessBoard.getButton(i).setOnAction(newEventHandler<ActionEvent>() {@Overridepublic void handle(ActionEvent event) {int col =GridPane.getColumnIndex((Button)event.getSource());if(!chessBoard.isFull(col) && !lock){int j =chessBoard.addChess(col);if(chessBoard.isWin(col,j)){lock = true;chessBoard.setBtsOff(-1);}chessBoard.printInfo(col,j);chessBoard.changeLight();}//ifif(chessBoard.isFull(col))chessBoard.setBtsOff(col);}//class});}}public void addQuitEvent(){chessBoard.getChoice(1).setOnAction(new EventHandler<ActionEvent>() { @Overridepublic void handle(ActionEvent event) {System.exit(0);}});}public void addRestartEvent(){chessBoard.getChoice(0).setOnAction(new EventHandler<ActionEvent>() { @Overridepublic void handle(ActionEvent event) {chessBoard.clearBoard();lock = false;}});}}五、问题和讨论1.总结归纳JA V A程序开发的过程首先要正确安装JDK,并配置环境变量。

相关主题