|
This document contains answers to some commonly
asked questions in COS 126. If you know of a question that
many people have unnecessarily been struggling with,
please send email to
wayne@cs with
the subject
"COS 126 FAQ". The list is broken up into the following
general categories.
|
My program doesn't work. I try to compile it and it
just list and endless stream of errors. Should I just give up?
No! Everyone makes such mistakes - they're called syntax errors.
This means your code does not conform to the very rigid rules
of C syntax. Get used to it.
If your program doesn't compile, look at the first error message
and try to figure out what you did wrong. A single typo can
generate a very long stream of error messages, so don't despair.
The compiler will give you a line number along with a description
of the error. Identify the first error and try to fix
it. Recompile and repeat this process until it
compiles.
My program compiles but doesn't give the "right" answer. Should I just give up? No! If your program compiles, but doesn't work properly, you will need to determine what went wrong on your own. (These errors are often called bugs, because in the old days a moth might fly into the computer, and the code that you had labored over painstakenly for days would no longer work. In fact, this was the $1 million question on the Who Wants to be a Millionaire gameshow.)
For small programs, the printf method is often the quickest and most effective approach. There are more powerful methods for experienced programmers (see gdb below), but these require a bit of effort to master. The idea of the printf method is to print out the values of variables, including index variables in a loop. This will help you pinpoint where the problem is occurring. Figure out where the computer did something different from what you intended. Sometimes, it is as simple as accidentally using = instead of == in a logical expression.
My program still doesn't work. Help me please! Before you become excessively frustrated and violent, seek advice from classmates, lab assistants, and preceptors. Sophomores are also quite useful. They have all experienced the same frustration at some point in their programming career and will be very sympathetic.
However, before you seek advice, isolate your problem as best you can. Try to find a minimal piece of code that still exhibits the problem. Isolating the problem is an important skill, and it will benefit you in the long run. Once you have done this, bring this to your lab assistant or preceptor for advice. When they determine what's wrong, ask them how they discovered it. Learn from your mistakes.
I'm totally lost, and I don't even know how to begin coding. What should I do? Usually, the problem is more with the big picture of what needs to get done than with the actual programming. First, try to write down with pencil and paper a high-level flowchart of how your program will work. Try to fill in some of the details. After you have done this, consult with a lab TA or preceptor for advice.
How heavily do I need to comment my code? Ask your preceptor. Your code should be easily understandable by you and by the grader. Well written code often speaks for itself and needs little commenting. Always use consistent indenting to make your code more readable.
What's a readme file? It's a single text file (you can create it with emacs), that you will submit with every assignment. It should contain a brief narrative documenting what the various portions of your code do and how they do it. It should also include all of the output that the assignment asks for. Be sure to write this file carefully; the grader will read this file first. See /u/cs126/examples/readme for a sample readme file.
How do I check whether my files have really been submitted? Enter the Unix command "/u/cs126/bin/submit 1". It will list all of the files that you have submitted for Assignment 1.
Where can I find helpful clarification to the assignments and online versions of the sample code provided? Go to the Assignments page.
What are the basic skills needed to be a successful
programmer?
Steve Summit's list of basic
programming skills includes: attention to detail, stupidity,
good memory, and the ability to abstract on several levels.
|
When I login to a machine in the 101 lab, I get the "black screen of death". If this is your first login on these machines, it's possible your configuration files are screwed up. If you know how to login to your account using telnet, then do this, and type the following command:
Now try to log back in to a 101 lab machine. If this doesn't work, consult a lab TA or go to CIT at 87 Prospect./usr/princeton/etc/userconfig/updatedots
What should I do if one of the 101 lab machines is showing
the "black screen of death"?
Do not use that machine. Ask a lab TA to reboot it. Unlike your home
PC's, you can do damage by turning on and off these machines without
following the proper procedure.
|
Can I work from home? Yes, we recommend reading Notes on Working from Home first. The notes are written specifically for Princeton COS 126 students.
I can't save a file in emacs remotely with Ctrl-x Ctrl-s from my MacIntosh. What's wrong? The default CIT telnet setup maps Ctrl-s to "suspend output" and Ctrl-q to "resume output." These are antiquated commands. Go to the menu "session", select "setup keys", and delete the last two entries. (It may also be possible to use Ctrl-x s instead.)
When I run emacs from a telnet session, it just hangs. This may happen if arizona thinks your terminal is capable of displaying X-windows. Try typing "emacs -nw hello.c" instead. If your terminal really is capable of displaying X-windows, use ssh instead of telnet.
Can I write my C code using Windows instead of Unix? Yes, a version of the lcc compiler is available for Windows 95 - NT. Adventurous souls can look into lcc. Your programs must still view and compile properly under Unix, and some assignments require you to use Unix.
Is there a more "Windows-friendly" compiler available? You can use other products, such as Microsoft Visual Studio, but remember that your programs must still compile properly on arizona (or on any other ANSI C compliant compiler).
Are there other clusters capable of running X-Windows? According to CIT, the X-Windows emulator MI/X on their Windows machines. It is unsupported, but here are their directions. The public cluster in the E-Wing of the equad on the 4th floor does support X-Windows, but is not staffed with lab assistants.
How do I enter the EOF signal from my PC or Mac keyboard? EOF means end of file. By default, it is usually Ctrl-z on PC's and Ctrl-d on Mac's.
I've been writing my programs on a PC, but when I transfer them over to Unix, my file is littered with weird "^M" characters. Then I have to manually remove each of them in order to get the program to compile. Type "dos2unix < hellodos.c > hellounix.c".
Under Linux, I compile my program, but when I type
"a.out" I receive a message that it can't find the file.
The current directory is not in your path.
Try typing "./a.out" instead.
|
I need help with Unix. Where can I find some guidance? The optional course textbook Harley Hahn's Student Guide to UNIX is a good hardcopy reference. There are also many electronic references. Unixtools contains several Unix tutorials, some for beginners, and some for more advanced users. Also, check out the web site Unix Help for Users.
My program goes into an infinite loop. How to I stop it? Don't worry. Every programmer writes code that does this from time to time. On Unix, type "Ctrl-c" to break out of the loop. Under no circumstances should you turn off a Sun machine. Seek assistance if you cannot stop the program on your own.
How do I get the backspace key to work? The "erase" function may have been mapped to the delete key instead of the backspace key. Either use the delete key or change your shell as described below. Alternatively, an ugly fix is to enter the Unix command "stty erase ^H". Here ^ means Shift-6.
What's EOF? How do I put it into my file? How do I enter it from the keyboard? EOF means end of file. It is automatically the last character of every file. To enter it from the keyboard, it is usually "<Return> Ctrl-d" by default.
The Unix command "lpr hello.c" doesn't work. Instead it reports _default: unknown printer. There is no default printer setup. The printer in COS 101 is named psr. Use the Unix command "lpr -Ppsr hello.c" to print your file. Alternatively, use the Unix command "setenv PRINTER psr" and "lpr hello.c" will work.
I accidentally deleted my file hello.c. How can I recover it? There is no "Recycle Bin" in Unix. When you delete a file, it is gone. You can email restores@phoenix to have CIT restore your file from their tape backup. First, you might want to check that hello.c didn't end up in the wrong directory by accident. Second, you may have a file ~hello.c in your directory: this is a backup created by emacs. If it is sufficiently recent, type "mv ~hello.c hello.c" to rename.
How can I print my code in two column format? Use our customized version of the program enscript. For example,
will print 2-columns per page, in landscape, with a header at the top of each page, but no cover page.enscript126 hello.c
I accidentally named my program hell.c. What do I do? The Unix command "mv hell.c hello.c" will rename the file appropriately.
How can I clear the Unix screen? Use the command "clear".
Where can I find a tutorial or cheatsheet for emacs? Type Ctrl-h t in emacs to get an on-line tutorial. Here's an emacs cheatsheet
I can't write any files. I get the error message write: Disc quota exceeded. You have used more disc space on arizona than CIT permits. Type
to see how much space you've used, and how much you're allowed to use. CIT gives you woefully little. Delete unnecessary files, especially large PostScript files. To determine which files are consuming the most room, use the commandquota -v yourusername
to get a list of all directories, sorted in reverse order of how much space they consume.du | sort -n
How can I get the output of a.out into a readme file? You can use the X-Windows cut-and-paste options. A more systematic way is to enter the Unix command "a.out > readme". This redirects the output of a.out into the file readme (instead of to the screen). You can still input data from the keyboard (e.g., if your programs call scanf). However, the screen will be blank, as all output (including printf statements) goes to the file, not the screen.
How can I get the output from several programs into one readme file. The Unix command "a.out > readme" overwrites the original readme file. Use "a.out > readme" the first time. This creates the file readme, and puts the output of a.out into it. If the readme files already exists, use the Unix command "a.out >> readme" to append to it.
What does !! do? It is shorthand for re-running the previous Unix command. Also, the command "!gc" will re-run the most recent Unix command that starts with gc, perhaps gcc myprogram.c
What exactly is piping? We only answer the question with respect to Unix. :) Piping connects the standard output stream of one Unix program into the standard input stream of another. This is best demonstrated by example. To send the output of a.out to the printer, you could enter the following three Unix commands. "a.out > temp, lpr temp, rm temp". The first command redirects the output of a.out to temp. (See above.) The second prints the file temp, which now contains the appropriate output. The third command cleans up and removes the file temp. The Unix command "a.out | lpr" does the same thing, without creating and deleting the intermediate file.
If I telnet to arizona, how can I exit out of emacs and compile my C code? The emacs command Ctrl-x Ctrl-c exits you out of emacs permanently. The command Ctrl-z temporarily suspends emacs and lets you type in Unix commands like gcc hello.c. To return to emacs type the Unix command fg which puts emacs in the "foreground".
How can I compile my code from within emacs? See customizing emacs below. After you have done this, just type Ctrl-c Ctrl-c and the Return key and emacs will automatically compile your file, creating a window to display any error message. If there are errors, type Ctrl-c Ctrl-n to jump to the next error.
How can I customize emacs? If you ran the setup126 program in the Hello World assignment, you should already have the compilation features mentioned above. Also you will get auto-indenting of your C code. Finally, if you use xemacs it will add some nice coloration to your otherwise drab display.
What is xemacs? It's an extended version of emacs with a nicer graphical interface. If you have access to it, use the Unix command xemacs hello.c & to try it out.
What is command line editing and file name completion? Command line editing lets you recall previous commands using the arrow keys. Also you can use emacs style commands to edit it. File name completion is when the computer finishes the name of your file after you enter the first few characters. If file name completion is enabled, you can type emacs he followed by the Tab key. It will complete it to hello.c. Of course, it depends on what files are actually in the current directory. You may need to change your shell (see below).
How do I change my shell to tcsh? The shell is the program that processes your Unix commands. The tcsh is a fancier version of the standard shell. Simply type the Unix command tcsh to change it. To permanently change your shell, enter the Unix command chsh. It will ask you for your password and the new shell. On the arizona machines, it is /usr/princeton/bin/tcsh. Ask a lab assistant for help if you are unsure. As an added bonus, the backspace key should work properly.
Where can I learn more about grep. See pages 11-25 of Unix Tools for Text Processing. The two sample text files used are virgin and wizard
Where did the name grep come from? The original UNIX text editor "ed" has a construct g/re/p, where "re" stands for a regular expression, to Globally search for matches to the Regular Expression and Print the lines containing them. This was so often used that it was packaged up into its own command, thus named "grep". According to Dennis Ritchie (of K+R), this is the true origin of the command.
Are there any automated ways to help me debug my programs? To tell the gcc compiler to report more possible errors and warnings, compile with
or gcc126 for short.gcc -ansi -pedantic -W -Wall -O2 myprog.c
The GNU debugger gdb is useful for finding semantic errors. Not needed in COS 126, but useful for creating large pieces of code. Check out the following gdb tutorial. Here's a gdb cheat sheet.
Sun Workshop (Forte) is a professional integrated development environment (IDE) that is already installed on the arizona system. You can access it via the "Workshop" button in xemacs or by typing the command "workshop". Here is a link to some documentation.
Is there any automated way to "beautify" my C code with consistent indentation? Automatic indentation in emacs is described above. The Unix program cb will make your code consistent with the style found in Kernighan and Ritchie. A slightly more sophisticated version is called indent. Here's a sample style format:
or indent126 for short. Use the command "man indent" to see what all the options are.indent -st -di3 -i3 -nce -bad -bap -npsl < oldhello.c > newhello.c
How can I view Adobe Acrobat or .pdf files from Netscape? If it's not already setup, on Unix machines you should go into the Netscape 3.04 Options menu and select General Preferences. Then select Helpers. Scroll down to where it says application/pdf. Highlight and click Edit. Check Application and type acroread %s in the box. Now when you click on a .pdf file you can view it automatically.
How can I run a recent version of Netscape on the arizona machines? On arizona, the Unix command "netscape &" will run some version of Netscape. To run a more recent version you may need to use "/usr/princeton/netscape/netscape-4.6/netscape &" instead. Ask a lab TA for assistance if you want to make this your default.
Is there a spelling program for Unix? Type "ispell filename".
What does Unix stand for anyway?
It is not an acronym, but is a pun on "Multics". Multics is a
large operating system that was being developed shortly before
UNIX was created. Brian Kernighan (of K+R) is credited with the name.
|
Uninitialized variables. All variables must be initialized to some value (often to 0 or NULL) before they can be used. Be sure to reinitialize them to their original values when appropriate.
Reversing order in assignment statement. In C, = means assignment, not mathematical equality. To replace the value of a with the current value of b use a = b; not b = a;
Assignment vs. logical equals. In C, = means assignment and == means logical equals. To test if two integers represent the same number, use if (a == b) not if (a = b)
Logical AND vs. bitwise AND. In C, "&&" means logical AND, e.g., "if (x >1 && x < 2)". In contrast, "&" means bitwise AND, e.g., if x is an integer, then "x & 15" is the rightmost 4 bits in the binary representation of x. Similarly, "||" means logical OR, and "|" means bitwise OR.
Logical XOR and exponentiation. In C, "^" means bitwise XOR. Use the math library function pow to do exponentiation.
Not giving scanf a pointer as input. The function scanf requires its arguments to be pointers (not integers or floats) so that it can change their values. Use scanf("%d", &a); not scanf("%d", a);
Extra ; before body of loop. A semicolon at the end of a for or while statement is not part of the syntax. Instead it is treated as an empty statement. So, i = 0; while (i < 17); i++; will cause an infinite loop.
Extra ; or = after #define. The line "#define N 100;" will replace occurrences of N with "100;" instead of "100". The line "#define N = 100" will replace occurrences of N with " = 100" instead of "100".
Chaining multiple < operators. The statement if (x < y < z) does not mean what it does in mathematics. Instead, you must break up the compound statement into two separate conditions joined by logical AND: if ((x < y) && (y < z)).
Forgotten ; after struct definition. The following code will produce a core dump.
as the program will try to return a struct Rational from main() instead of an int.struct Rational { int num; int den; } main(void) { }
Off by one errors. C arrays are indexed starting at 0, not 1. So, if a is an N element array. you should use
instead offor (i = 0; i < N; i++) a[i] = 0;
for (i = 1; i <= N; i++) a[i] = 0;
Characters vs. Integers. The declaration char c; provides storage for a character (typically an integer between 0 and 255 or between -128 and 127). Do not use for reading in input with while ((c = getchar()) != EOF) since EOF does not have the value of any character. EOF is always negative; on most systems it is -1. If you use char c you may never detect the end-of-file, or you may get a spurious end-of-file signal if EOF casts to the same value as an input character.
Int vs. Float. The following code won't work.
The "%f" signifies float, but it is read into an integer variable.int a; scanf("%f", &a);
Float vs. Double. The following code won't work.
Use %lf with scanf() instead of %f for doubles. Paradoxically, you should still use %f with printf() for doubles.double d; scanf("%f", &d);
Pointers vs. Arrays. The following code won't work.
String literal are not (necessarily) modifiable. Instead, usechar *p = "hello world!"; p[0] = 'H';
char a[] = "hello world!"; a[0] = 'H';
Following a NULL pointer. If link x = NULL when your program accesses x->key or x->next, then your program performs an illegal operation. This causes a segmentation fault error at run-time. Use lcc -n myprog.c to compile your program to eliminate these notorious bugs.
Mismatch of format specifiers with printf().
The statement "printf("%f", 17);" will not work as expected,
unless you replace 17 with 17.0.
The variadic function printf() will try to print to
the integer 17 as a real number. The arguments to printf()
are not automatically casted to the type specified by the format string.
|
Is there a general C programming FAQ? Yes, here's the C programming FAQ. It contains many more difficult questions and answers than the ones presented here.
Where can I find a good on-line introduction to C? Steve Summit maintains a very nice set of C programming notes. You will also find detailed and inciteful comments about the Kernighan and Ritchie text.
Where can I find a good tutorial on C pointers? Some students have reported that Ted Jensen's tutorial is a godsend. Pointers are a more advanced C programming topic that aren't covered until the middle of the course, so if you don't know what a pointer is yet, don't worry until they're covered in lecture.
What's the history of the C programming language? Here's Dennis Ritchie's article on the Development of the C Language.
I already know C. How can I further develop my programming skills? COS 126 is designed to teach only introductory programming skills. You will learn "industrial strength" programming in COS 217, and more advanced data structures and algorithms in COS 226. The Valladolid Programming Contest Problem Set contains hundreds of problems of varying difficulty. You can submit your C programs for electronic judging. Two highly recommended books for motivated students are Programming Pearls by Jon Bentley and The C Programming FAQ by Steve Summit.
What's the difference between a local and global variable? Local variables are defined at the beginning of a function. They can only be used within that function. It is fine for different functions to use the same variable names. But, each function only knows about its own local variables. Global variables are (usually) defined at the beginning of the file, not inside any function. They can be accessed and modified by any of the functions within the file.
What's are parameters and arguments of a function? Arguments are used to pass information to a function. The expression f(10,2) calls the function f with two arguments, 10 and 2. Suppose we had a function int f(int m, int n) {return m - n*n ;} The function f has two parameters, m and n. When called, the parameter m is assigned the value 10 and n is assigned the value 2. The parameters m and n can be used just like local variables (see above) within the function f. Thus f(10,2) returns the value 6.
I get crazy results with the sqrt and other math functions. Be sure to #include <math.h> in your program. Also, make sure that other functions returning doubles are correctly defined.
The compiler complains when I try to use the sqrt and other math functions. Depending on your setup, you may need to tell the compiler to use the math library, e.g., "gcc hello.c -lm".
The math library function pow doesn't work with integers. Why not? All math library functions return type double. You will need to "cast" to get things to work.
I get imprecise results when doing arithmetic with floats and doubles. For example, the statement printf("%f", 3.0 * 1.0 / 3.0); might print out 0.999999 instead of 1.000000. Floating point arithmetic is not done exactly. The computer stores the numbers in binary, so do not be surprised to see roundoff error. This can be especially troublesome when you are trying to compare a very tiny number with 0.0. You should write code that does not depend on such roundoff imprecision. It is possible to write an ADT to work with arbitrary precision; however, doing arbitrary precision arithmetic will be significantly slower than with the built-in float and double types.
Instead of printing out a number, the computer prints out NaN. What's going on? NaN stands for "not a number." It occurs when you apply an illegal operation (divide by 0) to a floating-point number.
My program crashes before it ever executes the first statement in main. What's going on? You probably have an array that is too large.
What's the difference between ++i and i++? Both ++i and i++ increment i by one. They differ in when the increment is performed. For example, suppose i = 17. Then the statement x = i++; sets x=17 and then increments i to 18. In contrast, the statement x = ++i; first increments i to 18, then sets x=18.
What does i = 5; a[i] = i++; do? Undefined. Depending on your compiler, it might set a[5] = 5, or a[6] = 6. This statement is undefined, so the compiler can do anything at all, e.g., set a[5] to 17 or reformat your hard drive.
What's the difference between "int *px;" and "int* px;"? Nothing, the compiler treats them exactly the same.
What do "segmentation fault" and "bus error" mean? In general, your program tried to access memory that it shouldn't have. The cause is likely: uninitialized pointers, inadvertent use of null pointers, mismatched function arguments (especially scanf).
Give me an example of a segmentation fault. Here's the simplest way to generate one. link x = NULL; x->key = 17;. Of course the problem is that you are trying to access the key field of x but it doesn't exist. A similar thing would happen if you write x->next = y; since the next field of x doesn't exist either. This seems like a simple thing to avoid, but often occurs when you change the link x, say in a for loop, so that it sometimes points to a real node and sometimes points to NULL. Here's one way to pinpoint the segmentation fault: replace x->key = 17; with if (x != NULL) x->key = 17; else printf("Here's the seg fault!\n"); An easier way is to compile your program with lcc -n. Now, when you run your program, code is automatically inserted to check for following null pointers.
How do I get printf to print a % sign? printf("%%");
What should go in the .h header file? In general, the header file should contain macros, structure definitions, typedef declarations, global variable declarations, and external function declarations.
I've heard from a serious C programmer to never use scanf. What should I do? For COS 126, scanf is perfectly fine. However, it is nearly impossible to do proper error checking and recovery with scanf. A more refined method is to use fgets with sscanf.
I've heard from a serious C programmer to never use gets(). Yes, there is no way to use gets() safely. It is the most dangerous function in the C library, and its usage has led to several computer viruses. Use fgets instead.
Are goto statements really that evil? After doing the TOY programming assignment, you will see that for and while loops are much better at controlling program flow than goto statements. Here's a reprint of Dijkstra's 1968 article Go To Statement Considered Harmful.
How should I generate a random integer between 0 and N-1? Unfortunately, with most compilers rand() % N is notoriously bad, but that's good enough for COS 126. Some better alternatives include rand() / (RAND_MAX / N + 1) or (int)((double)rand() / ((double)RAND_MAX + 1) * N). If you really need a better random number generator, try the Mersenne Twister.
Where can I find really bad C code? Check out the International Obfuscated C Code Contest for some really horrific examples. It takes quite a bit of C knowledge to write or decipher these nasty programs written by some of the world's best programmers.
Is there a program that will convert my C code to html? Check out Code2html.
I've heard about a new version of C called C99
or C9X. What is this all about?
It's the latest ANSI/ISO standard that specifies exactly
what the C language is. There aren't yet any C99 compliant
compilers, but here's
Here's a
list of changes between the two versions if you're interested.
It includes Boolean types, variable-length arrays, and declarations
in the middle of a block.
|
What is PostScript and how do I create it?
PostScript is a stack-based language that is used by many
printers. Printers have built-in computers that translate
the PostScript language into printed output.
A PostScript program is a text file (just like a C program).
You will write a C program that creates a PostScript program!
Use printf statements to print the PostScript
program to the screen. Then use redirection to output it to
a file, e.g., "a.out > picture.ps".
Are there any good references for PostScript? Yes, check out A First Guide to PostScript. The PostScript Language Reference Manual provides more complete documentation. It is available online, and is on reserve at the Engineering Library.
How do I view and print a PostScript file? To print a PostScript file named picture.ps, use the Unix command "lpr picture.ps". The printer will realize that it is a PostScript program, not just a regular text file. Before printing, make sure that your PostScript program works properly by viewing. The Unix command "gs picture.ps" will "compile" the program and set up an X-window for you to view it. You can't do this over a telnet session.
How do I view and print a PostScript file on a PC or Mac? You can download the PostScript viewer Aladdin Ghostscript 5.50 from the Ghostview home page. Be sure to download the version for your platform (Unix, Windows, DOS, Mac). Also note that version 6.0 does not yet come bundled with a viewer, so the easiest thing to do is use version 5.50.
How do I put comments into my PostScript program? The % in PostScript is analogous to // in C. Upon seeing a %, the rest of the line is ignored. There is one exception - the first line of a PostScript program must begin with %!.
Could you describe PostScript commands for drawing graphics? Here are some of the most common ones.
What is the unit of measure for the PostScript coordinate system? By default, one unit is 1/72 of an inch. On an 8.5 x 11 page, the lower left corner is (0,0) and the upper right is (612,792).
What are the standard colors in rgb format? Red, green, and blue, are (1,0,0), (0,1,0), and (0,0,1), respectively. Black is (0,0,0), white is (1,1,1). Cyan, magenta, and yellow are (0,1,1), (1,0,1), and (1,1,0), respectively. Here's a color palette in PostScript.
How do I draw a single path that has several colors? You can't. Each path in PostScript must be drawn the same color. So you need to break up your path into pieces, and color each one individually. This can be done by individual moveto and lineto commands. If you are using relative coordinates (e.g., with rlineto) then you may not know where to move to to begin the next path. In this case, use the command currentpoint to push the current point onto the stack and use it to start the next path.
0 440 moveto 1 0 0 setrgbcolor 512 0 rlineto currentpoint stroke moveto -120 rotate 0 1 0 setrgbcolor 512 0 rlineto currentpoint stroke moveto -120 rotate 0 0 1 setrgbcolor 512 0 rlineto stroke
|
Where can I learn more about Java?
Go to www.javasoft.com
or
www.gamelan.com.
These widely used sites have on-line tutorials and loads of
information and
sample applets. Also, if you like the Deitel and Deitel
C book, they have a book for Java too. (The Sedgewick book will
be available in Java eventually.)
Here's
documentation for all Java 1.2 classes.
Where can I download a free Java compiler for Windows? Go to www.javasoft.com. The latest version is (at least) 1.2.1. A full installation requires about 65MB.
Is there a good editor like emacs to use with Java? Under Unix, emacs works for Java just like it does for C. Under Windows, you can use Notepad - it doesn't have the same functionality as emacs, but will do the job.
Is there a Java FAQ? It's available at www.afu.com.
Where can I find some really great Java demos? Check out www.jars.com. Stand back. Much of the source code is available, so you can use it as a starting point to design your own sophisticated Web applet.
How can I run Java 1.2 instead of Java 1.1 on arizona? By default the arizona machines are setup to run Java 1.1. You are better off using Java 1.2. Use /usr/java2/bin/javac and /usr/java2/bin/appletviewer instead of javac and appletviewer.
I can't get appletviewer to work on arizona. What's wrong? First, make sure that you have compiled MovingBall.java with the command javac MovingBall.java. Then the command appletviewer MovingBall.html should work fine on the arizona machines. On some machines, the DISPLAY variable needs to be changed from :0.0 to localhost:0.0. In principle, these are the same, but it appears to cause a problem with appletviewer. To change it, type the Unix command setenv DISPLAY "localhost:0.0".
I can't get my Java program to work under appletviewer or Netscape on my PC. What's wrong? You may not have the latest version of the Java Runtime Environment. You can download from www.javasoft.com. It's about 10MB.
How come my Java program doesn't work under Netscape or IE? Older versions of Netscape and IE do not support all of the features in Java. You probably need Version 4 or later (maybe even 4.5). In arizona type netscape-4.7 instead of netscape.
When I update my java file, it does not get updated in my web browser, even after hitting the Reload button. Why not? First, you must javac your program again. Then, in Netscape use Shift-Reload; in Internet Explorer, use Ctrl-Reload.
For debugging in C, I use the "printf method." How can I do the same thing in Java? Use the method System.out.print or System.out.println as used in the lecture notes. Output will be written to the arizona prompt, rather than to the Java window, but this should be sufficient. Note that there is no formatted printing in Java (i.e., can't use things like %9.3f).
If I run appletviewer, the output of System.out.println goes to a Unix window. Where does it go in Netscape? In Internet Explorer? In Netscape 4.7 use the menu option "Communicator-Tools-Java console". In IE 5.0, use the menu option "View-Java Console". You may have to check the "Tools-Internet Options-Advanced-Microsoft VM-Java console enabled" option first.
How do I create an array in Java? You can't do "int a[256];" as in C. Instead, use "int a[] = new int[256];". The keyword "new" is needed to allocated memory for the new object.
What's a class? It's the idealization of an ADT - a data structure along with associated functions to manipulate the data.
What's an object? It's a particular instance of the class. An object of class Rational is a single rational number.
What's a method? A method is one of the functions associated with the data in the class. For class Rational, a method might be add.
How do I allocate memory for a new object? There is no automatic memory allocation for data objects in Java (except for intrinsic data types like int). There is no malloc either. Use the new operator, e.g., r = new Rational(3,8).
What's a constructor? It is the method that gets called when you initialize a new object with the operator new. The constructor shares the same name as the class.
What is overloading? Whenever a class has two methods with the same name, but different arguments, the method is overloaded. Java knows the data types of each object, so it knows to call the appropriate overloaded method, depending on the arguments.
What's a static data element or method? It's a data element or method that is not associated with an individual class object, but rather with the class as a whole. This plays the role of a global variable. A good example is the static variable N in Nbody.java which counts the number of Body objects.
What are public and private data elements and methods? Public data elements and methods can be accessed by any class. Private members can only be accessed by other members of the same class.
What are final data elements and methods? A final data element is one whose value can't be changed after initialization. A final method is one that can't be overridden by classes that inherit it.
What is this? The keyword this within a method is a reference to the object itself.
What are try, catch, finally, and throws used for? Java supports (and enforces) exception handling. Functions return not only their value, but also any errors that occurred (e.g., division by zero, not enough memory).
What is garbage collection? In C you must explicitly return memory to the system with free when you're done using it (otherwise you get memory leaks). In Java, the system is clever, and periodically checks to see which memory you are done with, and reclaims it.
What does extends do? Java supports (single) inheritance. The declaration class Nbody extends Applet means that the new class Nbody will inherit all of the data object and methods of the built-in parent class Applet. Objects of a subclass will have access to all of the non-private data and function members of the parent class. This includes support for graphics and a user-interface.
What does super do? For a subclass, the super keyword refers to its parent class.
What is overriding? Whenever a method in a subclass has the same name and arguments of a method in the parent class, the subclass method will replace the previous definition. The methods show, run and start are overridden in Nbody.java.
What is the control flow of an applet? An applet first calls methods init, start, and then paint. The paint method is called automatically each time the window is moved or resized. The method repaint calls update then paint. In Nbody.java, the start and update methods are overridden.
What is multi-threading? Multi-threading enables multiple program to run concurrently, without any one of them hoarding all of the system resources. The Java language directly supports multi-threading. This is done in Nbody.java. The run method of Thread is overridden.
What is a "deprecated method"? It is a method supported in the current version of Java, but may not be supported in future versions. You should try to avoid using these obsolete methods. Java changes so quickly that sometimes it is hard to keep up!
How can I read in an integer/double from the
keyboard?
It's not so easy to do on your own. The easiest way is
to download the class EasyIn from
www.afu.com.
|
Where can I find a humorous account of the history of operating systems. Here's In the Beginning was the Command Line by Neal Stephenson.
Where can I learn more about floating point precision? Here's What every computer scientist should know about floating-point arithmetic by David Goldberg. It's quite detailed and it's only meant as a reference if you're quite interested in the subject.
Where can I find a sample Turing machine simulator? Here's a TM that tests if one number divides another.
I want to know more about Alan Turing and John von Neumann. Here's the Alan Turing home page. Here's a biography of von Neumann. Here's information on Enigma and the Turing Bombe.
Where can I find Turing's original paper on the Turing test? Here is his 1950 paper Computing Machinery and Intelligence.
Where can I learn more about the history of computing? Visit the Virtual Museum of Computing.
Where can I find a formal statement of the P versus NP problem? Here is a link to Stephen Cook's description of the problem via the Clay Mathematics Institute. You can also claim a $1 million prize from this Web site if you solve the problem!
Where can I learn more about the algorithms and data structures? There are many Web sources including this online course. See also COS 226.
Where can I learn about quantum computing? Visit the Centre for Quantum Computation.