Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
COMP110 Practical 2
Using the Departmental Linux Systems
1 Introduction
This practical is intended to familiarise you with the departmental Linux systems and relates to
the following two module learning outcomes:
• To effectively use relevant software packages and appreciate different types of software;
• To effectively use general IT facilities including organising your file store, taking advantage of
access control and security features of operating systems.
The tasks described below will guide you through the process of accessing and logging onto a Linux
system, using the Linux desktop, using command line interfaces, editing text files, and creating,
compiling and running Java programs under Linux.
This document is available in PDF format at
http://intranet.csc.liv.ac.uk/~ullrich/COMP110/notes/practical02.pdf
While you work through the tasks below compare your results with those of your fellow students
and ask one of the demonstrators for help and comments if required.
2 Logging in to the Linux systems
The lab PCs running Windows are only part of the department’s computing facilities. There are
also a number of systems running the Linux operating system (currently Scientific Linux 6.3), which
are available to all members of the department. These machines are not physically accessible, but
can be accessed over the network. You use the same (Computer Science) username and password
to log in to both the Windows and Linux systems (and also the new Apple Mac lab), and they all
provide access to the same shared filestore.
Commence by logging in to the Windows PC in the same way as you did previously. Now
double-click on the “Unix (Exceed)” shortcut on the left-hand side of the desktop. After
a short pause you will be presented with a list of machines that form part of the department’s
Linux facilities (Figure 1a). You need to choose the one you want to use. It does not matter which
machine you choose, as they should all be configured identically1. The top entry in the list is
usually the most sensible, since it was the first to respond (and hence presumably the one under
the lightest computing load). However, you can also take into account the number of users and
choose the one with the lowest number of users already on it.
Select one of the machines now by double-clicking on it which will then display a login prompt
(Figure 1b) for that particular Linux PC. Once you have successfully logged on, using the De-
partmental user name and password, you will be presented with the Linux Desktop Environment.
Notice that the Windows taskbar is still present at the bottom of the screen and it shows Exceed
as one of the applications that is now running. The Exceed window has the usual title bar at
the top. As far as the Windows system is concerned, the Exceed session is simply another local
application, which can be minimised, maximised, or closed, just like any other. If you want to
1But please note that when reporting problems with the Linux systems, you should make a note of which one
you connected to - more on how to do this later.
1
(a) List of Linux systems (b) Login Prompt
Figure 1: Logging in to Linux
bring the Windows desktop back to the ‘foreground’ use the keyboard shortcut ‘Windows Logo
key + D’. For more on keyboard shortcuts see https://support.microsoft.com/en-gb/help/
12445/windows-keyboard-shortcuts.
3 The Linux desktop
Everything contained within this Exceed window is actually running on the (remote) Linux system.
How the desktop looks and behaves is controlled by a particular type of application called a
“window manager”. There are a number of different desktop environments available on the Linux
system - by default you will be using the “Gnome” environment. (You could have changed that
by clicking on the icon in bottom right corner of the login screen.)
The Gnome desktop is similar in both appearance and behaviour to the Windows desktop
you were exploring last week (strictly speaking the Gnome desktop traces its roots back to the
X Window system which was developed at about the same time as Microsoft Windows and Apple’s
Lisa Office System; so, this is not a case of imitation, but a case of coevolution). There is a taskbar
at the bottom of the desktop, a toolbar at the top of the desktop, and a series of icons on the left
side of the desktop (Figure 2). Taskbar and toolbar are instances of panels.
Note that Windows has a single taskbar containing the list of running applications, quick-start
Figure 2: Gnome Desktop
2
icons and the Start Menu. In contrast, the Gnome desktop separates the running programs (at the
bottom) from the quick-start icons and menus (at the top). However, panels are easily configurable
and it is up to you whether you want to merge both taskbar and toolbar into a single panel. Also,
it is possible for you to add your favourite applications to one of the panels. This, as well as
changing other properties of a panel, is done by right-clicking on an empty space on the panel.
Finally, do not get confused between the Gnome desktop menus and the Exceed title bar
immediately above it.
Figure 3: Workspace
manager configuration
By default the Gnome desktop has more than one workspace enabled2
In the right-hand corner of the taskbar you see the workspace manager
or workspace switcher. It shows you two virtual workspaces and indicates
that you are currently working in the left-most workspace. You switch to
a different workspace by clicking on it in the workspace manager. You
can add more workspaces by right-clicking on the workspace manager and
selecting the option “Preferences”. This brings up the configuration tool
for the workspace manager (Figure 3).
A typical user of the Gnome desktop would use a different workspace
for each of the different tasks that he/she currently performs as part of
their work, e.g. one workspace for email reading, one workspace for web
browsing, one workspace for Java program development, etc.
4 Starting a web browser
We will look at the operation of the Linux Desktop in more detail shortly. But the next task is to
use a web browser to access the PDF file for this practical. Just as under Windows, a choice of
web browsers exists under Linux, including Mozilla Firefox and Google Chrome (but luckily not
Internet Explorer). In the following we are using Firefox. Start this web browser using the menu
selection “Applications > Internet > Firefox Web Browser” (Figure 4). This will bring up the
Figure 4: Starting Firefox
Firefox start page or the departmental home page. You need to find the web page for the notes
for COMP110, exactly as in Practical 1. The URL is:
http://cgi.csc.liv.ac.uk/~ullrich/COMP110/notes/
2Multiple workspaces have been a recent addition in Windows 10, although third-party software for workspaces
existed for earlier versions of Windows. Unix-based systems had multiple workspaces since 1990.
3
After navigating to that web page, look for the PDF file for Practical 2 and open it.
5 Handling windows in the Linux environment
Having opened the Firefox web browser window, you should find the program listed in the taskbar
at the bottom of the desktop, just as last week with your web browser on Windows3. You should
also notice that a small solid rectangle has appeared in the workspace manager.
Figure 5: Linux file manager
For the rest of this practical, keep the web browser running on
one workspace, and switch to another workspace to complete the
various exercises. Notice how the contents of the outlines change,
as you open and close new application windows.
Switch to the second workspace, and double-click on the
icon, labelled “〈userId〉’s Home”. This will open a file manager
application, showing a view of your peronal filestore (Figure 5).
Notice how the contents are the same as your H: drive under
Windows. Use the minimise button on the Exceed window to
switch back to the Windows desktop to check this. (But be careful
not to close the Exceed window altogether!)
The Linux file manager can be used to create, delete or rename
files and folders, and to move them from one location to another. The file manager window (along
with every other application window) also has a title bar, containing minimise, maximise and close
buttons . These can be used to manipulate the size and location of the window on the
desktop, in much the same way as under Windows. Practise moving and resizing the file manager
window, as well as moving and renaming files and folders within the file manager, until you are
comfortable with how these work. Also try right-clicking on the title bar, to see what happens.
6 Command line interfaces
Although Windows and Linux desktops are primarily graphical environments, they both also pro-
vide a command-line interface, allowing you to type commands into a “terminal window” and see
the results as text-based output.
For COMP101, you will be expected to compile and run your Java programs via the command
line. We’ll look at exactly how to do this shortly. But first, let’s look briefly at simple uses of the
command line on both systems.
On Linux, you can start a shell window by opening the “Applications” menu from the toolbar,
expanding the menu “System Tools” or “System”, and selecting the entry “Terminal”. Under
Windows, the equivalent “Command Prompt” is found at the top of the “All Programs” list. The
two terminal windows look fairly similar (Figure 6), and both initially just contain a shell prompt,
typically, bash-4.1$. This prompt, which will be represented throughout this practical by $ or >,
is followed by a square or underline—the cursor. Anything you type on the keyboard will appear
here. You can use the left and right arrow keys to move the cursor back and forth within the
command you have entered, and this can be used to correct typing errors.
3But note that it only appears in the Linux taskbar - it isn’t present in the Windows taskbar. Windows only
sees the main Exceed application - everything else is invisible to it.
4
(a) Gnome terminal (b) Windows 10 command prompt with properties
Figure 6: Terminal windows
When you have finished typing the command, press the  key. This tells the shell to
run the command you specified, and report the results. It will then display another prompt, ready
for your next command. Here is an example that uses the hostname command to discover which
Linux machine you are using:
$ hostname
linux06.csc.liv.ac.uk
Throughout the rest of this practical, we will not show the command prompt in the examples.
6.1 Basic use of the command line
The simplest commands are those concerned with viewing and manipulating files and folders. The
following series of commands illustrate this for both Linux and Windows. Try working through
each set in turn, and watch what happens using the file manager (note: ‘l’ is the letter `, not
the number ‘1’). The examples assume that in Practical 1 you have created a directory structure
exactly as suggested. You have to adjust the examples if you have used different directory names
or a different directory structure.
Linux MS Windows
cd cd H: Start in your home filestore
pwd pwd Show the current directory
ls -l dir Long listing of the files and
folders in this directory
cd year1/comp110 cd year1\comp110 Move into a sub-folder
ls dir /w Short listing of files and
folders in this directory
cd .. cd .. Move back up a level (.. =
“parent directory”)
cat myBooks.txt type myBooks.txt View the contents of a file
more myBooks.txt more myBooks.txt View the contents one page
at a time (press the ‘q’ key
to quit)
cp myBooks.txt test copy myBooks.txt test Make a copy of a file
mv test test1 rename test test1 Rename a file
mkdir myDir mkdir myDir Create a new folder (direc-
tory)
5
Linux MS Windows
cp test1 myDir copy test1 myDir Make a copy of a file in a
different folder
mv test1 myDir/test2 move test1 myDir\test2 Move a file into another
folder (and rename it)
ls myDir dir myDir List the contents of a folder
rmdir myDir rmdir myDir Try to delete a (non-empty)
folder (which fails)
mv myDir/* . move myDir\* . Empty the folder (by mov-
ing the contents to the cur-
rent directory)
rmdir myDir rmdir myDir Delete the (empty) folder
rm test1 test2 del test1 test2 Delete the test files
Be careful when using rm. Linux assumes you know what you are doing. So, if you ask it
to delete a file, then it will be deleted. It will not simply be moved to the “Wastebasket” folder
(which is what the file manager does). So it’s typically not possible to “undelete” a file that has
been deleted by mistake—when it’s gone, it’s gone. The same holds for Windows and del.
Note that Linux uses a filesystem with case-sensitive identifiers—the folder Year1 is different
to one called year1. Be very careful to type the names of files or folders exactly as they appear in
the file manager, or in the output of ls or dir. Windows is more forgiving, and will ignore case
differences.
Also be aware that by default Windows Explorer will often hide the filename extension - the
last three or four characters after the final ‘.’. When using the command line, you typically need
to give the full filename, including the filename extension.
6.2 Wildcards
The third-from-last command above (emptying the test directory before deleting it) illustrates a
new idea—the use of “wildcards”.
Most of the commands above specify the name of a file or folder to work with. And as the last
command shows, it’s often possible to manipulate several files at the same time, by listing them
on the command line. But if there are large number of files to manipulate, typing all of them
out would be both time consuming and subject to errors. So both Linux and Windows provide a
wildcard mechanism, to match the names of multiple files (or folders) at once.
Create two copies of the textbook file, using cp myBooks.txt myFile1 and cp myBooks.txt
myFile2. Note that you may have given the textbook file a different name and that it may be in
one of the subdirectories of your home directory. Make sure that you are in the right directory
and that you adjust the commands to fit with the filename that you have used.
Next, try the following sequence of commands. Think about the results you see, and what
these patterns might mean.
$ ls myFile?
$ ls *
$ ls *.*
$ ls *.txt
$ ls myFile*
$ ls *File?
6
Also try the corresponding commands with the Windows command line (using dir instead of
ls).
6.3 Redirection
Another useful technique is “redirection”, where the output of a command can be saved to a file.
$ ls myFile* > out.file
$ cat out.file
This can be very useful when you come to test your Java programs. But note that any errors
will still be displayed
$ ls yourFile* > out2.file
ls: cannot access yourFile*: No such file or directory
$ cat out2.file
Redirection works on both Linux and Windows command line terminals.
The main problem with this approach is that it only saves the output of the program, and
not anything that is typed on the keyboard. Redirecting output to a file also means that you
won’t see any prompts or instructions that might be displayed by the program. In one sense, this
doesn’t really matter - as long as you know what information you need to supply, you can type
this “blindly” and the program should run correctly.
But it would be better if you could see the output (including any prompts) and still have
everything saved to a file. On Linux, this can be done using the script command:
$ script -c "command " out3.file
(where the -c option specifies the command to be run and capture). Try experimenting with
this, using some of the commands above. (Although it will only really become useful when you
start running programs that expect input from the keyboard). Note that script is only available
on the Linux systems - there isn’t an equivalent mechanism under Windows.
6.4 Pipes
A variation of output redirection is the idea of a ”pipe” - using the output of one command as the
input to another. Try the following in the Linux terminal window
$ ls | sort -r
$ cat myBooks.txt | tail -5
$ ls /lib | less (press the ‘q’ key to quit)
(The symbol ‘|’ is to the left of the character ‘z’ on UK keyboards.) Compare the results of
these pipeline commands, with the output generated by the first command in each pipeline on its
own. Also, find out what the difference between less and more is.
Pipes are also available under Windows, though they are much less widely used. The last com-
mand would work in much the same way (dir C:\Windows\System | more). Windows doesn’t
typically include the same range of “filter” commands such as sort, head and tail4.
Most (traditional) Linux commands are designed to process the contents of the specified files,
or (if no files are listed) to work on “standard input” as part of just such a pipeline of commands.
4Although these commands are actually available on the departmental Windows system, as part of the Cygwin
package.
7
6.5 Command line history
When developing a computer program, you’ll typically find yourself repeating the same sequence of
commands again and again - editing the file containig the source code, compiling this file, running
the resulting program, editing the file to fix any errors, compiling the corrected file, running the
program again, and so on. This means that you will end up typing the same commands over and
over again.
Both Linux and Windows command shells include a command history mechanism, which re-
members the previous commands that you have typed and allows you to recall them and run them
again. Try using the up and down arrow keys to step through this list.
6.6 Filename completion
There is one final function of the shell to mention, namely, filename completion.
Quite often you will have several different files in the same folder, with significantly different
names. The Linux shell allows you to type the first few characters of a filename (sufficient to
uniquely identify that file), and then hit the  key. This will automatically complete the
name of the file, just as if you had typed it at the keyboard. This is extremely useful - particularly
if you are using meaningful filenames (which can be relatively long), or if your typing is not
particularly accurate!
If the prefix you have supplied is not unique, and there are two files that could possibly match,
the shell will complete as much as it can, and leave you to complete it.
7 Editing text files
Linux offers a plethora of text editors. We will just mention two here: The default text editor
gedit and Emacs. (The Atom text editor unfortunately not yet installed.)
Use the file manager to find the file myBooks.txt that you have created in the previous practical
and double-click on it. This will open the file in a simple text editor called “gedit” (Figure 7a),
which is the default editor for most types of text files.
You can also invoke this directly by clicking on the “Applications” menu in the top left corner
of the desktop, expanding the “Accessories” submenu, and selecting “gedit Text Editor” near
the top of the list. The operation of this editor is similar to Notepad++, which you saw last
week. Experiment with adding and deleting text from the file, both using the keyboard and via
cut-and-paste.
Now use the file manager to find the file HelloWorld.java from last week, right-click on it,
select “Open With > Other Application . . . ”, then select “Emacs” among the options offered.
This opens a different editor called Emacs (Figure 7b). Again, the basic operation is very similar
to the other editors that you have been using. Both gedit and Emacs also use syntax highlighting
to indicate the structure of your code (as you saw with Notepad++ or Atom in Practical 1).
For any given file, there will typically be a range of applications that can sensibly be used to
view or edit it. You can choose between these by right-clicking on the file, hovering over the “Open
With >” menu entry, and selecting from the list that appears. You can use any suitable text editor
to write your code, on either the Linux or Windows systems (but remember what you’ve been told
about the use of IDEs).
8
Figure 7: Linux text editors
8 Compiling Java programs
In the last practical you created a Java program called HelloWorld.java. This file contains the
source code which is readable text, designed to be understood by the programmer. In order for the
computer to be able to run the program, this code must first be compiled into Java Byte Code.
This binary “class” can then be executed by the computer in order to actually run the program.
Both of these steps involve typing commands into the (Linux or Windows) terminal window.
Start a terminal window under Linux, change to the directory in which you have stored your
Java program, and ensure you can see the file HelloWorld.java in the output of ls. If it’s not
there, use the file manager to locate this file, and then use cd in the terminal window to move to
the same folder. Ask a demonstrator for help if you are not sure about this.
Then run the command
$ javac HelloWorld.java
If this compiles successfully, then the command will complete without displaying any further
output, and you should now have a file HelloWorld.class in the same folder. If you see errors
produced by the compiler, or the class file is not present, then open the HelloWorld.java file
in your preferred text editor, and check that the contents still match the code from last week’s
practical. Remember that on Linux, case matters—if the file is called HelloWorld.java, and you
type the command javac helloWorld.java, then the compiler will not be able to find it. The
Windows shell ignores case differences, so this command would be successful under Windows.
Again, ask a demonstrator for help if you get stuck.
Assuming that your code file has compiled correctly, you should now run the program, using
the Java interpreter command:
$ java HelloWorld
(without the .class suffix). This should produce the expected output string (“Hello, World!”).
Again, be careful about case—you should type the name of the class file exactly as it appears
in the file manager (or ls). Note that the class filename will always be the same as the name that
you have in the
9
Figure 8: Printing in gedit and Adobe Reader
class HelloWorld {
statement at the start of the code in the Java file. This will normally match the name of the Java
file, but it does not have to. If they are different, the class file will follow the code, rather than
the filename.
9 Printing
If you want to print your Java program, you can do so using “File > Print . . . ” in gedit. This will
open the print dialogue that lets you choose a printer and set your print preferences (Figure 8).
The two main printers available to you are ‘Print to File’ and ‘University’. ‘Print to File’
converts your file to PDF or PostScript, University refers to the “Follow-You” printing service
of the University just as we have seen under MS Windows in the previous practical. Again, make
sure before printing that you choose the correct printer setting, e.g. single-sided or double-sided.
Once you press the “Print” button, another dialogue window will open and ask for authentication.
Enter your University username, in the form livad\〈userId〉, and University password; see the
right-most image in Figure 8.
Most Linux applications have print dialogues identical or similar to the one that gedit uses.
10 Logging Off
While it is tempting to close the Exceed window using the “X” button in the title bar (or simply
log out of Windows directly), this is not a good idea. If your Linux session is shut down without
warning, the various Linux applications won’t have the opportunity to exit cleanly, and may leave
their internal configuration settings in an inconsistent state. This can cause problems when you
come to log in next time. This is a particular issue with the Firefox web browser.
Instead, make sure that you select ‘File > Exit’ (or equivalent)
from each of the application menus. Then open the “System”
menu in the toolbar, select the “Log out” entry, and confirm this
in the dialogue box that appears. This will now return you to the
list of Linux systems, that you saw at the start of the turial.
Click on the “Exit” button, and confirm this. You have now
safely closed down your Linux session, and can log out of Win-
dows, as before.
10