Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Lab 1: Introduction to Eclipse and Simple Data Definitions ► Fundamentals II Introduction to Class-based Program Design General Texts Lectures Syllabus Lab Materials Assignments Pair Programming Overview Code style Documentation ▼ Lab Materials Lab 1: Introduction to Eclipse and Simple Data Definitions Lab 2: Working with Self-Referential Data Lab 3: Testing Lab 4: Equality and using double-dispatch ► Lab 1: Introduction to Eclipse and Simple Data Definitions 1.1  CCS Accounts 1.2  Partners 1.3  Eclipse IDE 1.4  Hourglass 1.5  Lab Part 2 On this page: 1.1 CCS Accounts 1.2 Partners 1.3 Eclipse IDE Learn to set up your workspace. The First Project Set up the run configuration and run the program. 1.4 Hourglass 1.5 Lab Part 2 Introduction Making examples Simple Data Definitions Data Definitions with Containment Data Definitions for Unions of Data Self-Referential Data Bouncing Ball simulation 7.9     ← prev  up  next →  Lab 1: Introduction to Eclipse and Simple Data Definitions Goals: The goals of this lab are to get familiar with our work environment: the Eclipse IDE, the handin-server submission process, the basics of running a program in Java, and program testing framework. The second part of the lab will focus on practicing data definitions and examples in Java. Since this lab is happening before your first lecture, we ask that you complete the second part of the lab on your own time with your partner by the end of the week so that you are prepared for Homework 1. Related files:   tester.jar     javalib.jar     Shapes.java   1.1 CCS Accounts You will use Bottlenose to work on your homework sets, to keep track of revisions, and to submit your homework. You will need a CCS account to use Bottlenose so please go here to apply for an account if you don’t already have one. Important: if you have had a CCS account in the past, but are not a CCS student and your account has been deactivated due to inactivity, do not apply for a new account. Instead, send an email to systems at ccs dot neu dot edu explaining that you’re registered for CS2510, that your account has been disabled, and provide your CCS username and your NUID in the email. You will not likely be able to log in until the Systems team has a chance to process your account, so be patient. 1.2 Partners Just like in Fundies 1, almost all of the work you do in this class will be done with a partner. Please take the time to review the pair programming expectations on the course website. We will likely have 1-2 partner swaps throughout the semester, but you are free to choose your first partner. If you have a preferred partnership, both members should go ahead and request each other on the Handin server before the end of the lab. For instructions on requesting a partner see Section 6 of the Complete Guide to the Handin Server. If you do not have a perference for a partner and would likely to be matched randomly we will create partnerships after lab is finished. Partnerships in lab will work similarly to how they did in Fundies 1, but we will not be creating individual channels in Teams for each partnership. Instead, the expectation is that you will have a private call with your partner(s) and invite your tutor so that they can drop in and assist as needed. This means that you will also need to be on top of your notifications so that you are ready to come back to the general channel when requested. 1.3 Eclipse IDE Eclipse is an integrated (program) development environment used by many professional Java programmers (as well as programmers using other programming languages). It is an Open Source product, which means anyone can use it freely and anyone can contribute to its development. The environment provides an editor, allows you to organize your work into several files that together comprise a project, and has a compiler so you can run your programs. Several projects form a workspace. You can probably keep all the work till the end of the semester in one workspace, with one project for each programming problem or a lab problem. There are several step in getting started: Learn to set up your workspace and launch an Eclipse project. Learn to manage your files and save your work. Learn how to edit your Java programs and run them, using our tester library. Learn to set up your workspace. First, install the Java Development Kit (JDK): download Java 11 from http://www.oracle.com/technetwork/java/javase/downloads/index.html appropriate for your machine, and install it. Make sure you choose the JDK option, and not merely the JRE: the latter only enables you to run Java programs, but the development kit lets you develop them. Do not use any version higher than 11. The submission server does not support higher versions, so you may have some problems when you submit. Next, download Eclipse from https://www.eclipse.org/downloads/ – the standard Eclipse IDE is fine, and the Eclipse site should detect your computer’s operating system appropriately. When instaling it, select Eclipse IDE for Java Developers, for this is what you are becoming! Before opening the program (while it installs), follow the instructions below, replacing the reference to Z:\ with whatever folder on your computer is convenient for you. Create a workspace folder in your home directory where you will keep all your Java files. This should be in z:\EclipseWorkspace Note that z: is the drive that Windows binds your UNIX home directory, and you can name it something else if you really want to. Next, set up another folder in your home directory where you will keep all your Java library files. This should be in z:\EclipseJars We will refer to these two folders as EclipseWorkspace and EclipseJars. Make sure the two folders EclipseWorkspace and EclipseJars are subfolders of the same folder. Start the Eclipse application. The First Project Right click the following two libraries and select “Save link as...” Save them to your EclipseJars folder. The libraries you will need are: Related files:   tester.jar     javalib.jar   Create a project. Back in Eclipse, in the File menu select New then Java Project. In the window that appears in the Project layout section select Create separate folders for sources and class files. Important: If you hit next, you should see a checkbox asking to create a module-info.java file – it is important that you uncheck it. If you forget, you will have another chance when you click the Finish button: make sure you choose Don’t Create option to not create a module-info.java file. If you still forget, you will need to delete the module-info.java file that gets created. If you don’t, you’ll likely see cryptic errors complaining that “the package tester is not accessible” and that you “must declare a named package,” and your program will not run. (You will need to remember to do this for every project you create, unfortunately.) Select the Finish button to finish creating your project: we assume you have named it Lab1 in the instructions below. (The precise name of the project doesn’t matter, but it should not have spaces or any punctuation marks in the name.) If you now see in the main area of your screen a tab named “Welcome” and that has a lot of options, exit out of the tab by using the white x in the tab. Make the libraries available to the new project. You should see the Package Explorer panel on the left side of your screen. If the panel is not visible, go to Window menu, select Show View... then Package Explorer. You should also select Show View... Outline. Highlight your Lab1 in the Package Explorer panel, then right-click it and select “Properties” (likely the bottommost menu item). In the list on the left, select the Java Build Path, then select the Libraries tab. NOTE: If you are using Java 9 or higher, you should see two options in the main area of the form: “Modulepath” and “Classpath”. Make sure that you have clicked on “Classpath” to select it. If you do not see these two options, just ignore this step. On the right click on Add External JARs... The file chooser window will be shown. Navigate to your EclipseJars folder and select all jar files you have downloaded. Hit Apply and Close. Add the Shapes.java file to your project. Related files:   Shapes.java   Download the file Shapes.java to a temporary directory or the desktop. In Eclipse highlight the src box under the Lab1 in the Package Explorer pane. In the File menu select Import.... Choose the General tab, within that File System and click on Next. Browse to the temporary directory that contains your Shapes.java file and click “Open”. Click on the directory on the left, then select the Shapes.java file in the right pane and once you have checked the “Into folder” is Lab1/src, hit Finish. View the file Shapes.java. Click on the src block under Lab1 in the Package Explorer pane. It will reveal default package block. Click on the default package block. It will reveal Shapes.java. Double click on Shapes.java. The file should open in the main pane of Eclipse. You can now edit it in the usual way. Notice that the Outline pane lists all classes defined in this file as well as all fields and methods. It is almost as if someone was building our templates for us. Adjust the Eclipse settings. The Code style section explains how to configure Eclipse to only use spaces instead of tabs, and how to set the editor to show you the line numbers for all lines in the code. If you have trouble, ask a TA for help. Set up the run configuration and run the program. Highlight Lab1 in the Package Explorer pane. In the Run menu select Run Configurations.... In the list on the left, make sure “Java Application” is selected. Then, in the top left corner of the inner pane click on the leftmost item. (When you mouse over it should show New launch configuration.) Select the name for this configuration — usually the same as the name of your project. In the Main class: click on Search.... Among Matching items select Main - tester and hit OK. Click on the tab (x)= Arguments. In the Program arguments text field enter ExamplesShapes. Later, when you define your own program, you will use the class name of your Examples... class instead of ExamplesShapes. At the bottom of the Run Configurations select Apply then Run. Next time you want to run the same project, make sure Shapes.java is shown in the main pane (and is currently selected), then hit the green circle with the white triangle on the top left side of the main menu. (Running your program won’t do very much right now, because the code doesn’t do very much right now. But making sure that everything is capable of running is necessary before making your program more complex!) 1.4 Hourglass We will be using Hourglass to conduct exams this semester. Hourglass is an online exam server that is designed specifically for the needs of CS courses and balances exam integrity while avoiding intrusive lockdown browsers. If you have signed up for the course on the Bottlenose then once we have updated your registrations to synchronize with Hourglass, you should be able to sign in. If you are unable to sign in please let us know, but this synchronization is a manual process please wait until we’ve announced that we’ve synchronized the registrations before trying to sign in. 1.5 Lab Part 2 As mentioned before, the second part of this lab provides additional practice with data definitions but is better suited to be completed after the first lectures. As such, we request that you complete this portion of the lab with your partner on your own time before the end of the week. Although in general labs will not be graded, feel free to come to office hours with questions. NOTE: as this is the first week and we want to ensure you’ve gotten everything set up properly, you will submit a part of this lab as part of Homework 1. Introduction We start with designing data — designing classes of data that are connected to each other in a systematic way, showing that the Design recipe for Data Definitions can be used virually without change in a completely different language than we have used in the first part. The programs we provide give you examples of the progressively more complex data (class) definitions, and illustrate the design of methods for these class hierarchies. The design of methods follows the same Design Recipe we have seen before. The only difference here is that for classes that represent a union type (for example classes Circle and Rectangle that are both a part of the union type Shape, the conditional statement used in DrRacket inventory/template is replaced by the dynamic dispatch into the class whose constructor has been used to define the specific object. Making examples Add examples of data needed to describe the shapes in the following image (ignore the colors): You won’t be able to display this image yet: you’re only defining data right now, rather than using an image library to render it. Simple Data Definitions Problem 1 Here is a data definition in DrRacket: ;; to represent a School ;; A School is (make-school String Number Boolean) (define-struct school [name endowment has-football?])   (define UT (make-school "University of Texas" 30e9 #t)) (define streets (make-school "The Streets" 0 #f)) (define NEU (make-school "Northeastern" 800e6 #f)) Draw the class diagram that represents this data. Define the class School that implements this data definition and the class ExamplesSchool that contains the examples defined above. You should do this in a new School.java file. Right click the default package under Lab1 and select New > Class. Name it School. Run your program to make sure it works. Data Definitions with Containment Problem 2 Modify your data definitions so that for each school we also record its location. For each school’s location we only record the city and the state; each of these should be its own field. Create a Location class to contain the location information, then modify the School data definition to include a Location. Draw the class diagram for this data definition Define Java classes that represent this data definition. UT is in Austin, Texas; The Streets are in Baltimore, MD; and Northeastern is in Boston, MA. Make examples of these data and add two more schools. Data Definitions for Unions of Data Problem 3 An amusement park’s attractions include shows, food vendors, and roller coasters. Every attraction has a name and a price (in cents — so we have whole numbers only). Each show has a minimum age in years. Food vendors also have a short description of what kind of food and drink it sells. For a roller coaster we note the minimum height in inches required for riders, a rating of how exciting it is for riders, and a rating for how nausea-inducing it is. The integral ratings should range between one and ten, inclusive, with one meaning minimally exciting/nauseating and ten being extremely so. Define classes to represent each of these kinds of attractions. Think carefully about what type each field of each class should be. Do you need to define any interfaces? Construct at least two examples each of shows, food vendors, and roller coasters. Self-Referential Data Consider the following Fundies 1 style data definition for a Villain: In the grand tradition of Scooby Doo miscreants and Mission: Impossible baddies. ;; A Villain is one of ;; -- String ;; -- (make-mask Villain String) ;; interpretation: either a villain wearing a mask, described as a string, ;; or the true identity as the person's name. (define-struct mask [villain description]) Convert this data definition into Java classes and interfaces. What options do you have for how to translate this into Java? Make examples of Villains, including one with at least three masks. Bouncing Ball simulation In BSL if you wanted to define a Ball, it might look something like this: ;; A Ball is a (make-ball Number Number Number Color) (define-struct ball (x y radius color))   (define b (make-ball 0 0 5 "blue")) In Java, that same definition looks like this: import java.awt.Color;   class Ball { int x; int y; int radius; Color color;   Ball(int x, int y, int radius, Color color) { this.x = x; this.y = y; this.radius = radius; this.color = color; } }   class ExamplesBall { Ball b = new Ball(0, 0, 5, Color.BLUE); } In Java, x, y, radius, and color are all called fields. They are attributes of a ball. After all, balls are fairly pointless... A ball on its own is useless. What’s more interesting is doing something with a ball! Now, in BSL, if we wanted the area of a ball, we would have a function that looked like this: ;; Ball -> Number ;; Returns the area of a ball (define (area b)   (* pi (sqr (ball-radius b)))) But this approach can quickly get messy. And wouldn’t it make more sense for the ball to know its own area? That’s where methods come in. In Java, functions that live inside objects are called methods. These methods can use the data that’s inside the objects, as in the below example. import java.awt.Color;   class Ball { int x; int y; int radius; Color color;   Ball(int x, int y, int radius, Color color) { this.x = x; this.y = y; this.radius = radius; this.color = color; }   // Returns the area of this ball double area() { return Math.PI * Math.pow(this.radius, 2); } }   class ExamplesBall { Ball b = new Ball(0, 0, 5, Color.BLUE);   boolean testBalls(Tester t) { return t.checkInexact(b.area(), 78.5, 0.001); } } Note the use of this.radius. What this is doing is referencing the number we gave the ball when we created it. In this example, ball b has a radius of 5, so the area of b should be somewhere around 78.5. If you need the radius of another ball, you can access it with otherBall.radius. This works for the other fields as well. Also note the use of checkInexact. The area of the given ball is roughly 78.5, but not exactly. In fact, all comparisons with floating-point numbers cannot be done completely precisely, so whenever we need to test such values, we must use checkInexact instead of the more familiar checkExpect. The last parameter, 0.001 specifies the tolerance we’re willing to accept: here, we’re saying the two values must be equal to within 0.1% (or a factor of 0.001). Problem 4 Design a circumference method for Ball. Problem 5 Design a distanceTo method for Ball. It should take a Ball and calculate the distance between each Ball’s center. Problem 6 Design an overlaps method which returns a boolean indicating whether the ball overlaps with another, given Ball. Challenge Problem Do all of the above again, this time with a Rectangle class! You’ll need x and y positions, as well as width, height, and color. Then, design a diagonal method for Rectangle that calculates the length of the diagonal inside the Rectangle. Problem 7 Related files:   bouncing.jar   For this problem, you will need the bouncing.jar file above. Add it to your project the same way you added the other jar files. This contains some basic BigBang code specific to Bouncing Balls. For now, you don’t have to learn how BigBang works with Java. That will come a little later in the course. Create a new project BouncingBalls. Then, create a file called Ball.java. Copy the below code and start filling in the gaps. import tester.Tester; import java.awt.Color; import javalib.worldimages.*;   class BouncingBall { Posn pos; Color color; int size; int dx; // how fast is the ball moving to the right? int dy; // how fast is the ball moving downward?   BouncingBall(Posn pos, Color color, int size, int dx, int dy) { // TODO: FILL IN YOUR CODE HERE }   // Returns a new BouncingBall that's just like this BouncingBall, but moved // by this BouncingBall's dx and dy BouncingBall move() { // TODO: FILL IN YOUR CODE HERE }   // Returns a new BouncingBall that represents this BouncingBall just after // it has bounced off a side wall. Does not actually move the ball. // This method will be called automatically when `collidesX` returns true BouncingBall bounceX() { // TODO: FILL IN YOUR CODE HERE }   // Like bounceX, except for using the top or bottom walls BouncingBall bounceY() { // TODO: FILL IN YOUR CODE HERE }   // Detects whether the ball is colliding with a side wall. boolean collidesX(Posn topLeft, Posn botRight) { // TODO: FILL IN YOUR CODE HERE }   // Detects whether the ball is colliding with a top or bottom wall. boolean collidesY(Posn topLeft, Posn botRight) { // TODO: FILL IN YOUR CODE HERE } }   class ExamplesBouncingBalls { int WIDTH = 300; int HEIGHT = 300;   // NOTE: We have provided BouncingWorld for you, in the starter code. // We'll see how it works in a few lectures boolean testBigBang(Tester t) { BouncingWorld w = new BouncingWorld(WIDTH, HEIGHT); return w.bigBang(WIDTH, HEIGHT, 0.1); } } Try running it and interacting with it and see what happens. Given what you know of big-bang from Fundies 1, does pressing a key seem to do anything? Does clicking the mouse?     ← prev  up  next →