Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Lab 01 - Intro to UNIX and Java LAB 01 - Intro to UNIX and Java Introduction Welcome to the first CS 180 lab! The purpose of this first lab is to walk you through getting started with UNIX and Java. If you have no prior experience with a UNIX-like environment, don’t worry. This lab will guide you through everything you need to know to accomplish simple tasks using a UNIX command line environment and to create a simple Java program. So, let’s begin with a discussion of what exactly UNIX is. UNIX UNIX is a class of operating systems descending from a system created in 1969 at Bell Labs. There are a tremendous variety of different UNIXes, and chances are that you are already familiar with a few. For instance, most current Apple products run on Mac OS X, which is a variety of UNIX. There are also many UNIX-like operating systems, which don’t meet the exacting specifications set up by the owners of the UNIX trademark, but are essentially UNIX. These include the Linux operating system and Google’s Android platform. Most of the Lawson lab computers run a variety of Linux called Gentoo, while the “lore” server set up for undergraduate CS use runs Solaris, which is a bona-fide UNIX. Accordingly, a very large amount of your time will be spent working in a UNIX environment; thus, it is worthwhile to learn UNIX well. If you are curious, more information on UNIX can be found here. Command Line What is the command line? The command line is a text-based system for communicating with a computer. Before the creation of the Graphical User Interface, or GUI, the command line was effectively the only way to use computers. The user would use the keyboard (since this was before the advent of mice) to enter commands to the computer, and receive results as text on the screen or on a printer. Even now, when GUIs have become the norm, the command line remains available in the form of a graphical program called a terminal emulator, which simulates typing commands and receiving output from a text terminal. This terminal emulator connects to a program called a shell, which does the job of interpreting the user’s commands, executing them, and outputting the results. Many different types of shells exist, but for this course, you will be using a shell called bash, which is among the most popular. How does the command line work? Open your computer’s terminal emulator by right clicking on an empty portion of the desktop, then clicking “Open Terminal”. (You can also access the terminal from the Accessories menu.) You should see something akin to: lore 51 /homes/[your login]$ This is the called the prompt, which is printed by bash to request a command from the user. Here, “lore” is the name of the computer you are currently logged into, “51” is the number of commands you’ve entered before this one, and “/homes/[your login]” is the current directory. Enter the command “ls,” by typing ls, then Enter. lore 51 /homes/[your login]$ ls [SOME OUTPUT] lore 52 /homes/[your login]$ Giving the computer the command “ls” asks it to list the contents of the current directory. After the results are printed, bash prompts the user for another command. If you make a typing mistake, you can edit what you have typed on the command line much as you would any graphical text box. Backspace, delete, and the arrow keys (left and right) all work as you would expect, and you can use them to correct any errors you make without retyping the entire command. You can pass arguments to a command by typing the command, then space, then its arguments, separated by spaces. Give the command ls with the argument “Documents”. NOTE: the Enter key is implied in this and following examples. lore 53 /homes/[your login]$ ls Documents lore 54 /homes/[your login]$ This asks the computer to list the contents of the directory named “Documents”, which should be empty unless you have put something in it. You can also pass special arguments called options, also known as flags. Options control some aspect of the functionality of a command. Most options are made up of a single letter, but there are a variety of different ways to pass options, so please try the examples below to get a feel for how options work. The option “a” tells ls to display all files and directories, including hidden ones, that is, those which begin with a period. Hidden files are not displayed by default. (NOTE: henceforth $ will represent the prompt, for brevity) $ ls -a The “l” option tells ls to display files in a vertical list, along with other information, such as permissions, owners, size, and modification time. Don’t worry about these things now, as they’ll be covered in more detail in the next lab. $ ls -l Options can be combined, like so: $ ls -a -l [output] $ ls -al [same output] $ ls -la [same output again] This asks ls to display all files, including hidden files, in the vertical list format. Some options are longer than one character. $ ls --all -l [same output yet again] This uses the long form of the option “a”, with exactly the same effect. Note that long options are preceded by two dashes. This is important, because otherwise, bash might think that “a”, “l”, “l”, were three single-letter options combined together. Finally, some options can take arguments: $ ls --color=always -w 20 This sets the option “color” to the value “always”, and the option “w”(width) to the value 20 (columns). The color option is particularly useful, as it allows you to easily distinguish files from directories.  It’s worth mentioning that you can combine single character options that take arguments with other single character arguments, but the one taking an argument must be the last. $ ls --color=always -aw 20 This yields color, a width of 20, and displaying hidden files and directories. One final point about arguments: How do you pass arguments that contain special characters like “-” or spaces? There are two ways: either surround with quotes, or escape the character with a backslash. For example, to list a file named “a b”: ls “a b“                OR ls a\ b Command entry shortcuts By this point, you may have noticed one of the downsides of using a command line: they require a lot of typing. Since not everyone can type >9000 WPM, most UNIX shells pro                                                                                            vide shortcuts that greatly reduce the amount of typing required. Two common and effective shortcuts are discussed below. Memorize them as soon as possible, and use them whenever possible. Tab completion The first of these shortcuts is tab completion. Tab completion allows you to enter only part of the path to a file or directory, and the shell will fill in the rest. Try using tab completion to list the contents of your “Documents” directory. Type “ls Doc”, but don’t press Enter:         $ ls Doc Now, press the Tab key, and bash will fill in the rest of the directory name. Then press Enter to run the command:         $ ls Doc[Tab] $ ls Documents/[Enter]         $ Now try doing the same, but with just “D”. Notice that when you press the Tab key, nothing happens. This means that more than one file or directory begins with “D”. Try pressing Tab twice again. You should see something like the following:         $ ls D Desktop/ Documents/ Downloads/ Pressing Tab twice causes bash to print the names of all files or directories that begin with what you typed. This allows you to quickly determine how much you have to type before you can use tab completion for the rest. Type “e”, then Tab, then Enter to finish the command and display the Desktop’s contents.         $ ls De[Tab]         $ ls Desktop/[Enter]         $ History The second way to reduce the amount of typing is to use the history to reuse old commands. Bash keeps a list of all the commands you have typed in the current session, that is, as long as a particular terminal window has been open. You can scroll backwards through the history by pressing the Up arrow key. You can return to entries you passed by pressing the Down arrow. You can rerun commands in the history by pressing Enter. You can also edit entries in the history to produce new commands. Note that you can never change the history entry for a command, but rather your new command gets added to the end of the history. Why use the command line? After all this talk about the command line, you may be wondering why anyone would want to use one. After all, didn’t mice, graphics, and GUIs replace the command line for a reason? If you have prior experience with the terminal before, you may know how difficult remembering the full array of commands and their syntax can be. Why go through all the trouble when GUIs exist to make things easier? The truth is that even today, much, if not most, serious work performed on UNIX systems takes place on the command line. This is not just a holdover from the old days; the command line has a distinct advantage.                                     GUIs are an option-based system, while the command line is expression-based. Consider opening a file in a program in Windows. You open the File menu, and select the Open option from the list. You are then presented with a list of files and directories. You browse through the folder structure, select the desired file, and press the Open button. At every stage of this process, you are presented with options in the form of icons, buttons, and menu items, and you decide between them. With a command line, you are not given any options to choose from, but must instead tell the computer exactly what you want it to do, all at once, in very specific terms. The command line shines through when you want to perform an action that is too intricate, specific, or unusual to be included in the options provided by a GUI. For instance, you may want to output the contents all files ending in .java, or all files that begin with the letter A and have a b somewhere in the middle, or all files that contain a phone number somewhere within their text. With a command line, all of these are possible: cat *.java cat A*b* grep -lE “[[:digit:]]{3}-?[[:digit:]]{4}” * | xargs cat That last one might seem a bit complicated, and it is. However, it would be much more complicated to do the same thing with a GUI. You would either need to find a specialized program or go through each file by hand, and there could conceivably be hundreds of files. With a command line, any action that is possible can be expressed, either as a single command, or as a sequence of commands. In fact, much of UNIX is built upon series of shell commands bound together in scripts. Thus, the command line trades away the simplicity of a GUI for monumental expressive power, which makes it very attractive to advanced users. Navigating the file system Now that you have some idea of the power potentially offered by the command line, you can begin exploring the more common UNIX commands. The first to learn are those that allow you to navigate the directory tree. By far, the most common command you’ll use in UNIX is ls. Much of the functionality of the ls command has been demonstrated in previous examples. Ls displays the contents of a specified directory or of the current directory if none is specified. Ls will also display the filenames of any specified files. This is useful for checking whether a particular file exists, as ls will report an error if it does not. There are two ways to specify files and directories as arguments: relatively and absolutely. The examples given previously have specified relative paths. The relative path of a file begins with the chain of subdirectories that leads from the current directory to the file, separated by forward slashes and ending with the name of the file. In previous examples, the files were located in the current directory, so only the name of the file was given. You can change your current directory using the cd (change directory) command. Try changing the current directory to the “Documents” directory with the following:         $ cd Documents The cd command changes the current directory to the one specified by its argument, or to your home directory if none is specified. In this case, the Documents argument is specified relative to the old current directory, your home directory. After running the above command, new relative arguments will be relative to the Documents directory. Now, you can list the contents of the Documents directory relatively:         $ ls The other way to specify paths is absolutely. Try $ ls / The forward slash by itself specifies the root directory. All directories in the UNIX filesystem are subdirectories of the root directory. A file’s absolute path is the chain of subdirectories that leads from the root directory to the file, separated by forward slashes and followed by the name of the file. Try displaying your home directory using its absolute path:         $ ls /homes         $ ls /homes/[your user name] There is a useful shortcut that can make typing this path easier. The tilde, “~”, stands for the absolute path of your home directory:         $ ls ~         $ ls ~/Documents UNIX provides two other essential navigation shortcuts: the special directories, “.” and “..”, contained within every directory. “.” stands for the directory itself, and “..” stands for the directory which contains that directory (i.e. the “parent” directory). Running the following commands should provide an intuition into how these work: $ cd $ ls . $ ls /homes/[your user name] $ ls .. $ ls /homes $ ls ../.. $ ls / One last point about paths: UNIX paths are case sensitive. Try the following:         $ ls ~/desktop ls: cannot access /homes/[your user name]/desktop: No such file or directory Error! “Desktop” and “desktop” are not the same directory. Make sure that you use the correct capitalization when referring to files and directories. Manipulating files and directories In addition to being able to navigate the filesystem, you need to be able to create, destroy, and relocate items within the file system. Create an empty file with the touch command:         $ cd $ touch bob         $ ls There should now be an empty file “bob” in the current directory. The touch command is intended to update the modification time of a file, “touching” it, but it is also commonly used for its side-effect of creating empty files. Display the current contents of the file with cat:         $ cat bob This won’t actually print anything, since, after all, the file is empty. Cat takes any number of files as arguments, then concatenates them together and prints out the results. Next, you should create a directory to store all of your files in this class. Use the mkdir command:         $ mkdir cs180         $ cd cs180         $ mkdir lab01         $ cd lab01 Now, move the test file into the new directory with the mv command:         $ mv ../../bob .         $ ls The mv command takes a source file or directory, and a destination file or directory. If the destination is a directory that exists, the source file or directory is placed inside that destination directory. Otherwise, the source is moved and given the name specified by the destination argument. In this case, since “.” is a directory (the current directory) that already exists, the “test” file is moved into it. Make a copy of the test file with cp:         $ cp bob bobcopy         $ ls Cp follows the same rules as mv, except the original file is not deleted. Of course, there is really no reason to have two empty files. Remove the copy with rm.         $ rm bobcopy         $ ls                                     It is very important to note that the command line offers no equivalent to Windows's “Recycling Bin.” Once you remove a file, it's gone for good. Make sure you really do not need a file before pulling out the rm command. Let’s make a backup of our lab01 directory, just in case something happens to it:         $ cd ..         $ cp -r lab01 lab01backup         $ ls         $ ls lab01         $ ls lab01backup The option r makes copy operate recursively, that is, it copies everything withing the directory. (NOTE: the mv command is automatically recursive; there’s no need to specify the r option.) Again, a backup of an empty directory is not the most useful thing of the world. Go ahead and remove it:         $ rm -r lab01backup         $ ls Again, the r option makes the command recursive. Be warned: THIS COMMAND IS EXTREMELY DANGEROUS. UNIX is powerful, but that comes with the assumption that you know what you are doing. You can wipe out your entire home directory with a single command, so, please, think VERY carefully before you use rm -r. Wildcards Create some empty files in the “lab01 directory”:         $ cd ~/cs180/lab01 $ touch testa.java testa.c test.java bob dot enzo Now, say you wanted to display all the java files in the current directory. You could do so like this:         $ ls         [write down all the files that end in .java]         $ cat [the name each and every java file] However, this is not an elegant solution. The shell provides wildcards to solve this particular problem. There are two shell wildcards: * and ?. * stands for zero or more characters, any characters. ? stands in for any one character. Wildcards make listing and displaying the java files much easier:         $ ls *.java         $ cat *.java You could also list all files that begin with test:         $ ls test* or all files that files with one character after test and before .java:         $ ls test?.java You can also use wildcards in paths, like this:         $ mkdir dira dirb dirc         $ touch dira/test1 dirb/test2 dirc/test3         $ ls dir*/test* This displays all files that begin with “test” in all directories that begin with “dir”. Man pages This lab has thrown a ton of information at you. You have already been introduced to quite a few different commands, each with their own syntax, arguments, and purpose. The subset of commands used in this lab are the most common, and by the end of CS 180, you will most likely have their basic use memorized. But until then (and even afterwards), UNIX provides an excellent way to look up information about commands: a tool called man, short for “manual”. With the exception of a few commands built into the shell (like cd), for any command, you can retrieve a full list of its functionality, arguments, and options with just this:         $ man [command] For instance, try looking up information on ls:         $ man ls To navigate within the “man page,” use the arrow keys to scroll up and down, and the Page Up and Page Down keys work like you’d expect. You can also use the Vim movement and searching keybindings, which you’ll learn about in a moment. You can exit the man page by pressing “q”. There is no shame in using man pages. Even old UNIX pros still refer back to them from time to time. They are very detailed, and, for the most part, very well written. So, if you ever find yourself unsure of exactly how a command works, the answers are just a man away. Text Editors - Vim So, now that you are able to create and manipulate files, you need to be able to fill them with useful content. Since this is a Java programming course, the useful content is in this case Java code. Thus, you need a way to enter and edit text, namely, a text editor.  Traditional UNIX text editors were entirely keyboard driven. There are two major UNIX text editors: Vim and Emacs. There happens to be a “religious” war between these two editors, so I refuse to offer an opinion over which is better. However, Vim is standard on essentially every UNIX system, while Emacs usually has to be installed. Thus, you should really learn Vim, since chances are you will be forced to use it at some point anyway. The first thing that you should know about Vim is that it is quite difficult to learn. It’s a bit like the shell in this regard. The movement commands aren’t immediately obvious, and what’s worse, the editor is modal. This means that the editor has several “modes” that determine what keypresses mean. Additionally, in only one mode does pressing a letter result in that letter actually being added to the document. This can be very frustrating for new users. Why bother? Well, the reasons are again similar to the shell. Vim’s commands are very expressive, and with a few clever keystrokes, you can save a few hundred. If you put effort into learning Vim well, it will pay you back tenfold in increased efficiency. Luckily, Vim comes with an excellent tutorial, called vimtutor. It is truly in your best interest to run through it, and try to learn to use Vim well. Run through the vimtutor now: (NOTE: A complete run through will take 20-30 minutes.)         $ vimtutor If you truly cannot get the hang of Vim, the graphical text editor gedit will serve you well. You can access it under Accessories -> Text Editor. First Java Program                  It is now time to create the traditional first program, “Hello world”, in Java. Create the the Java source file “Hello.java” in Vim (or gedit):         $ vim Hello.java Now, use Vim to give the file the following contents: public class Hello {         public static void main(String[] args) {                 System.out.println(“Hello, world!”);         } }                                     Now you can turn your program into an executable class file by running the java compiler, javac:         $ javac Hello.java         $ ls You should see the file “Hello.class” in the current directory. Finally, run the program using the Java Virtual Machine, java:         $ java Hello         Hello, world! Note that you don't need to specify the “.class” part of the file name. That's because the Java Virtual Machine takes as an argument the name of the class to run, not the file. The compiled version of the Java class “Hello” is contained within the class file “Hello.class”. Turnin So, you're finished with the main part of the lab. It's time to turn in your accomplishments so you can receive credit. To do so, you can use the command turnin, as follows:         $ cd ~/cs180         $ turnin -v -c cs180 -p lab01 lab01 The turnin command takes as arguments one or more files or directories to turn in. It also has two (essentially) mandatory arguments, c, which specifies the course to which the lab or project belongs, and p, which specifies the name of the project to which the files belong. The project name is in this case “lab01,” and this will be provided in the documentation for all future labs and projects. You can also obtain a listing of all open projects using the “l” option:         $ turnin -l For more details, a man page is available for turnin. Please note that turnin is not a general UNIX command, but a script found only on Purdue CS systems. Changing your password Before you leave the lab today, make sure to change your randomly generated password to something more memorable. You can do so using the aptly named passwd command: (NOTE: When you type your password, nothing will appear. This is a security feature).         $ passwd         Changing NIS password for dthornb         Old password:         New password:         Retype new password:         Changed password on NIS master lore.cs.purdue.edu Studies suggest that the optimum balance between security and memorability for passwords comes from length, not complexity, so try using a long, but relatively simple password. Piazza                                    This semester, CS 180 is using a system called Piazza to allow you to communicate with your instructors and classmates. You can use Piazza to post questions about projects or lectures, and instructors or other students can post answers. You should have already received an Email containing the link you need to create an account with Piazza. If you haven't, please let your TA know as soon as possible. Log in to Piazza now: https://www.piazza.com/ Piazza is not terribly complicated, so the best way to learn your way around the system is by diving in. Piazza has provided a sandbox environment that will show you around; you can access it by clicking on the gear icon in the upper-right corner of the webpage, then selecting “Piazza Help.” Then, click “The Basics” under the heading “Help Classes.” Command Quick Reference                                     For reference purposes, here is a table containing all the commands covered in this lab: ls List files and directories cd Change current directory touch Create an empty file (update modification time) cat Display the contents of files, concatenated together mkdir Create a new directory mv  Move a file, deleting the original. cp Copy a file, retaining the original rm Remove (delete) a file, permanently rm -rf Remove (delete) a directory tree, permanently man Access man pages (command documentation) vim Edit text files javac Compile Java source files java Run Java programs turnin Turn in labs and projects Conclusion                                    You should now be familiar enough with the UNIX command line to use it to perform some real work. You have been introduced to the commands for navigating around the UNIX file system, creating, deleting, and moving files and directories, editing text, and using the java command line tools. If you feel a bit overwhelmed, again, don't worry. Remember, you can get more information about any of these commands from the excellent man pages built into UNIX. In the next lab, you will learn more advanced UNIX techniques. Until then, take some time to play around with the command line, and you will be an old UNIX guru before you know it. Grading Successful turnin                100%