View Full Version : Java Class!
Welcome to Java Class!
We're going to learn a bit of Java here, one bit at a time, using real world examples to understand what we're doing. My aim is that all of the Java posted here is executable, so you can try it yourself.
First, before you can make use of any Java programs, you'll need two things: a compiler and a runtime environment. The compiler essentially just converts your text source files into a stream of bytes that can be executed directly by a physical processor, which doesn't have too many smarts. You could open up a hex editor and type in the actual bytes, but that would be very, very difficult! That's why compilers exist: to convert a human-readable program into a dumb-machine-readable one. The human readable file is called source code, and the machine-readable translation is called object code.
The second part, the runtime environment, is specific to Java. Unlike other languages, your Java code is not compiled for a specific physical processor, like a PowerPC G5 or a Pentium III. Instead, your Java code is compiled to neutral bytecode. This neutral bytecode resembles the PowerPC G5 and Pentium III instruction sets, but is not run directly. Instead, the bytecode is executed by a program that "pretends" to be a physical processor -- it's called a virtual machine.
Okay, so where do you get these programs? Here: http://java.sun.com/j2ee/1.4/download.html
You want the Java J2SE 1.4.2 SDK (Java 2, Standard Edition, version 1.4.2, Software Development Kit). The filename, if you're on Windows, is j2sdk-1_4_2_04-windows-i586-p.exe.
So, download and install that. When you're done, we'll be ready to compile and run our first program.
- Warren
Okay, so now you've run Sun's fancy installer, and it's all done. What now?
Look in this directory on your hard drive: C:\j2sdk1.4.2_04
The most important stuff for you to know is in the "bin" directory, which means "binary," or "executable programs."
Notably, in the C:\j2sdk1.4.2_04\bin directory, you'll find two programs that will be most useful to us: java.exe, and javac.exe.
java.exe is the runtime environment, which runs Java programs.
javac.exe is the compiler, which compiles Java programs from source code.
You can also walk around the C:\j2sdk1.4.2_04\demo\applet directory. You can launch the .html files, which include the appropriate links to load the applets in a browser window. You can also look at the source code for these applets, in the .java files.
- Warren
Now, how about compiling a program? I'm going to describe the old-school method, which uses the command line. Some people use JBuilder or Forte or other front-end development evironments, and you can also, if you'd like. I think it's useful to know what's going on at the bottom.
Create a new folder for your new project somewhere. Let's say I make a folder called C:\class.
Inside this folder, I'm first going to put a convenience file: make.bat, which will compile my code.
make.bat might look like this:
path=c:\j2sdk1.4.2_04\bin
javac *.java
and it simply runs the javac program on all files ending with .java in the current directory.
Now, we need to write a bit of Java code. Use this bit, and put it in a file called Test.java:
public class Test {
public static void main(String[] argv) {
System.out.println("Hello world!");
}
}
Don't worry about what it does just yet -- we just want to get the compiler fired up to make sure it works.
Now, open up a command line (Start->Run->"command") and get into your class directory (type "cd c:\class").
Finally, type "make" and hit enter, and you should see it run. You should now have a Test.class file in the your directory. You've compiled your first Java program!
- Warren
Now that you've got a Test.class file, you're all ready to run it.
First, I'll make another convenience file, run.bat, which simply frees me from having to type the full path of the java.exe program.
path=c:\j2sdk1.4.2_04\bin
java Test
When you type "run" on the command line, you're just running the java.exe program and telling it to run the program called Test, which is inside the Test.class file.
If it all goes well, you'll see "Hello world!" printed to your screen.
Let me know if you're following up to here -- you've now gotten past all the difficult first steps in getting your development environment set up, and you're ready to begin learning the Java language.
- Warren
1. Just as a naive question, can we define "program." I might get confused what we're talking about. Apparently (thanks to your concise delineation), what I used to call a program should actually be called "source code." Then, there's object code (which I don't quite understand). So what is a "program?" Is this just a synonym for "source code?"
The word "program" is used rather arbitrarily. Usually it does indeed mean "source code," but it can also mean "executable file." An executable file, is, of course, the result of compiling source code. Since there's a one-to-one correspondence between source code and the resulting object code, you can use the term "program" interchangably.
2. What's a "smart?"
Intelligence. What I meant by executed directly by a physical processor, which doesn't have too many smarts is simply that physical processors are designed to run only very simple steps, like "add this memory block to this memory block," not complex ones like "figure out what this programmer meant." The compiler's job is to figure out what the programmer means and generate code that can be run directly on the dumb processor.
3. Is "object code" the same thing as "machine code" or "machine language?" It seems like this would actually be a lot simpler than learning a foreign language. Well, I'm not here to argue, though :smile:
Object code and machine code are interchangable. Machine language, on the other hand, may refer to assembly language which is basically a mnemonic form of raw machine code that makes it a bit easier to read. Generally, I'd stick with object code or machine code.
4. I don't get this runtime environment thing. Is this just something like iexplorer? I mean, I thought that the whole point of compiling was to make an exec that could be run on any computer. Can you elaborate a little bit more on this. Is java special out of all other languages in this respect?
Java is special, because it has a purpose of being able to run on any computer, with any physical processor. You can compile your Java code on Windows and run it on Linux, for example. The way it accomplishes this is to compile to a platform-independent bytecode, which does not directly run on any physical processor. Bytecode is essentially machine code for a processor that doesn't really exist. Then a program called a virtual machine emulates that idealized Java processor on top of a real processor. Each platform (Windows, Linux, Solaris, etc.) has a Java virtual machine written for it. It effectively translates the bytecodes into real physical instructions the processor can run.
5. Do you think you could walk me through how to install these programs on the office computer. I may not have permissions (I think that's what it's called when the computer is set up to allow installations). I know it is running Win2000 service pack 4 from looking at start > control panel > system (of course, none of that really means anything to me, because, like I said, I'm computer stupid). I can pull up the Add/Remove programs dialogue. Well, I haven't tried anything yet, so this is just a heads-up that you might be hearing me complain about not being able to install this stuff. I suppose I could bring my laptop up here.
I'm afraid you'll have to defer to your office administrator.
6. What does it mean to "launch" an html file?
To open it with a web browser.
7. What's a convenience file and why is it needed? I thought that the compiler compiled, not some convenience file. This is exactly the kind of stuff that does confuse me. :confused: When you say, "it looks like this:" and there's some text, is this like a DOS command line thing?
The two convenience files (run.bat and make.bat) are only shortcuts. You could just type "c:\j2sdk1.4.2_01\bin\javac.exe *.java" everytime you want to compile your code, but you'd get tired of that. Instead, I just put those statements inside a file, called run.bat. Then, you can just type "run."
- Warren
Make sure that the "Test.class" file ends up in the same directory as your run.bat file. Test.class is created upon compilation in the same place as Test.java.
Forgive me for not mentioning the case sensitivity!
- Warren
What do you get by simply typing "java Test" on the command line?
- Warren
The line 'java Test' invokes java.exe, the Java virtual machine, and runs your Java program, stored in Test.class. If you got a Test.class file, it means compilation succeeded. If you're getting a "ClassDefNotFoundError," it means java.exe is also running properly. I'm not frankly sure why it's not finding Test.class on your machine. What version of Windows are you running?
You can also try running the command "java -cp . Test" (note the spaces). The dot by itself means "this directory," and "-cp ." means "classpath here in this directory." The classpath is the list of places where the JVM will look for classes. If you run it with "-cp ." you will force the Java virtual machine to look in that directory for its files.
I'll also attach a zip file with my files, which are apparently exactly like yours.
- Warren
What version of Windows are you running?98.
You can also try running the command "java -cp . Test" (note the spaces). The dot by itself means "this directory," and "-cp ." means "classpath here in this directory." The classpath is the list of places where the JVM will look for classes. If you run it with "-cp ." you will force the Java virtual machine to look in that directory for its files.Isn't this the whole point of:
c:\cd class
at the beginning of the procedure, though? Does java.exe only look at a specific directory if I type:
java Test
on the command line, or does it look all over the computer?
Well, the trouble you're having executing "java Test" may be a result of your running Windows 98.
Basically, there's an environment variabled called CLASSPATH. This variable contains a list of locations to search for .class files. It may or may not be set properly on your computer. When you just type "java Test," the java.exe program looks at your CLASSPATH variable, which might point to any number of places on your system. There's a good chance the very primitive Microsoft Java stuff that came with Windows 98 is setting up its own CLASSPATH.
So, to override it, just use the -cp switch on java.exe. In other words, type "java -cp . Test" and it'll force java.exe to look only in the current directory for class files. That should solve the problem. Lemme know what happens.
edit: I mean, edit the run.bat file so its second line is "java -cp . Test"
- Warren
I'm having trouble getting the applet to show. This is my code:
import java.applet.Applet;
import java.awt.*;
public class AppletTime extends java.lang.Object {
public AppletTime() {
}
public class Picture extends java.applet.Applet{
public void paint(Graphics g){
for (int x=0;x<251;x++){
g.drawLine(0, x, 500, x);
g.setColor(new Color(255,0,x));
}
}
}
public static void main(String[] args) {
}
}
I dont know what to do?
I think it has to show in Netscape Explorer, and I read something about making the code a superclass so it can run in Netscape Explorer but I'm not sure how to do it. Any suggestions?
First, your applet needs to be a subclass of Applet, not Object.
Second, you need to write an html document to include the Applet. You then open the html file with IE or Netscape or whatever.
Please see the examples in the demo folder. If you're using J2SDK 1.4.2, they'll be in c:\j2sdk1.4.2_04\demos.
- Warren
Guybrush Threepwood
Apr14-04, 09:51 AM
empire:
you could use the appletviewer utility which comes with the JDK to test your applet without writing an html document. of course if you use html not only you get to learn something new, but you can be sure the applet behaves as you intend.
Also as I know, a applet does not have a main() function, but instead has init(), start() and paint() ... what you have here appears an attempt to start an applet from command line (???)
Cool! Now, if someone can help exaplain stacks and queues, I'd be straight.
sunilkamadolli
Apr23-04, 11:06 PM
stack iz a data structure which follows last-in and first-out rule. that means the most recent data stored in the stack will be the first one to go out...
the queues follow the first-in and first-out rule instead.
UrbanXrisis
Apr25-04, 02:50 AM
Using threads, how do I make a string blink?
Guybrush Threepwood
Apr27-04, 01:47 AM
I think you might find an example in the JDK folder ... there are a couple of applets there.
But a quick thought is to make a while loop in the run() function in which you wait for t1 milisecs, draw the string, wait for t2 milisecs, erase the visible area .
Hmmm sorry to have neglected this thread. I need to consider what sort of code to post next... Any suggestions? Turin?
- Warren
Guybrush Threepwood
Apr28-04, 04:27 AM
maybe some basic file operations.... :)
chroot,
Apparently we are all going to use this thread as a message board, so I will make this my new default and leave all of my posts permanent.
Hmmm sorry to have neglected this thread.I just appreciate the fabulous job you did to get me started. I have been lately worried about finding a job and so have also neglected this java pursuit.
Hmmm sorry to have neglected this thread. I need to consider what sort of code to post next... Any suggestions? Turin?My initial/immediate goal is to be able to annimate ... I suppose that entails using java to display a series of gifs in a web browser one after another at a certain rate. I would like to learn how to do that for starters, so maybe you could organize such a program. I looked at (what I think is) the source code in the demo folder of that package I downloaded, but I could make just about 0 sense out of it.
I got the "hello world" to display, but all I learned from that is how to make the DOS shell display text, which I could do much more immediately before w/o the java.
I have absolutely no interest at all in annoying blinking text or anything related to web advertisement. Am I barking up the wrong programming language?
UrbanXrisis
Apr28-04, 03:24 PM
I think you might find an example in the JDK folder
Where is the JDK folder?
Hey turin,
Okay, let's begin with the simplest possible GUI first, to get you acclimated. I'll post the same code first without comments (so you can see the entire structure more clearly), and then again with detailed comments.
import java.awt.*;
import javax.swing.*;
public class Test {
protected JFrame frame;
public Test() {
frame = new JFrame("My First Window");
frame.getContentPane().add(new JLabel("Hello world!"));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] argv) {
new Test();
}
}
// The following two lines allow us to use classes like
// javax.swing.JFrame without having to explicitly
// include "javax.swing." every time.
import java.awt.*;
import javax.swing.*;
// Everything in Java goes in a class of some kind -- we
// just called this class Test.
public class Test {
// This is a variable which belongs to the Test class.
// Remember the definition of a class: it's a collection
// of both data, and the operations that work with that
// data. You can think of this variable as being "global"
// within the class, but not outside.
protected JFrame frame;
// This method, which has the same name as the class, is
// special. It's called a 'constructor,' and is the method
// that is called automatically when a Test object is
// created. The constructor's job, in every class, is
// to initialize the class's variables into a usable state.
public Test() {
// This line, with the "new" keyword, creates a new object.
// In this case, we're creating a new JFrame object, which
// is a window on the screen. We're passing one argument
// to the "new" operator, a string. That string is directly
// passed to the JFrame's constructor. The JFrame uses the
// string for the window's title.
frame = new JFrame("My First Window");
// Here we're wrapping two steps into one line. First,
// we're creaing a new JLabel object, with the text
// "Hello World" in it. Second, we're passing that
// JLabel object to the add method of the frame.
// In other words, we're creating a label and adding
// it to the window in one line.
frame.getContentPane().add(new JLabel("Hello world!"));
// JFrames start life hidden; you have to explicitly
// make them visible after creating them. We're going to
// first call the "pack" method, which packs all the
// JFrame's components into their best positions in the
// window, and then call "setVisible," with an argument
// of true, to show the window.
frame.pack();
frame.setVisible(true);
}
// This is the "main" function -- every program must have one,
// but you don't need to have one in every class; just the
// "toplevel" class. Since this program has only one class,
// it obviously must go here. For now, ignore the static keyword.
// This is a function that is accessible to the world (it's
// public), returns nothing (it's void), and accepts an array
// of Strings as an argument. The strings are the options typed
// by a user on a command line. If you typed 'java Test apple',
// for example, 'apple' would be in this array.
public static void main(String[] argv) {
// All we're going to do is create a Test object.
new Test();
}
}
Any questions?
- Warren
Any questions? :redface:
Uh, ya. Now I will probably really start to frustrate you.
Let's pretend that I don't speak programmer.
I am unclear about the meaning of the following terms:
- class
- variable
- method
- create
- object
- state
- component
I am unclear about the significance of the following issues:
- the first two lines: what they are and why you have them
- what it means to "use a class"
- how the Jframe object has been identified as "a window on the screen"
- what it means to be "in a class"
Affirmations:
- the amount of white space is inconsequential?
- the symbol "//" tells the compiler to ignore everything to the right?
Okay, let's start with the top, then. I thought you were perhaps already familiar with object oriented programming.
Basically, a program is broken up into components called objects. An object can (and often does) represent a physical object. For example, an object can represent a disk, or a file, or a printer.
An object contains two things: data, and methods. Data store the state of the object, while methods are pieces of code that operate on the data. For example, a printer object would store information like the printer's model number, whether or not it is out of paper, how much ink is left, and so on. The printer object would also have methods that can be called by a programmer. A simple method might be "print()", to which a programmer passes a page object to be printed. Another might be "getStatus()," so that a programmer can tell if the printer is busy or not.
How about another example? A chess game might include objects for pawns, rooks, bishops, and so on. Each object contains some state information (like the piece's position on the board) and some methods (like a move() method that tells the piece to move somewhere else).
So that's it: objects contain data and methods. The data encode the state, the methods operate on the state.
A class is like a blueprint for an object. A class describes the slots into which an object stores its data (they're called variables), and the actual code that makes up its methods.
For example, here's a simple ChessPiece class:
publc class ChessPiece {
public int x;
public int y;
public void move(int newx, int newy) {
x = newx;
y = newy;
}
}
The reason a class is a blueprint for an object is simple: I can make many ChessPieces. I can have 16 on a board, each one created from this blueprint. They would all be identical at the start. Each ChessPiece maintains its own independent x and y variables, and I have to specify which piece I mean when I use the move() method.
When you use the new operator to make a new object ("new ChessPiece(), for example, makes a new ChessPiece object), you're actually automatically allocating the space in memory for the new piece's x and y variables. You can say that you are creating a ChessPiece object from the blueprint.
Let's see about the other questions:
The import statements are just a convenience. The full, complete name of the JFrame class is actually javax.swing.JFrame, where javax.swing is a package of interrelated classes. For convenience, importing all of the javax.swing class (using the * for "all") allows us to use JFrame without having to specify its entire pedigree.
The JFrame class was written by some folks at Sun to work with your operating system to display a window. Hence, the JFrame class represents a window.
The variables and methods belonging to a class (like x, y, and move in the ChessPiece) can be said to be "in the ChessPiece class."
And yes, whitespace is ignored -- it's just for human readability. Anything to the right of // is considered a comment, and is also ignored by the compiler.
- Warren
chroot,
Do you teach a programming language? You would be an EXCELLENT instructor! I have spent weeks trying to read through Visual C, C++ books, but they never made sense to me. What you have said is - beautiful. OK, enough smoke up the ***. I'll have to dedicate the evening to absorbing all of this and get back to you tomorrow.
turin,
I have indeed taught programming classes in the past; I'm glad you find my writing so helpful, even when it's not all that well-organized and somewhat rushed!
- Warren
chroot, just one question if i may. My current connection is too slow to download that, but MS visual studio says that it contains "visual j++", do you know anything about that? Thanks.
Is that something I'd have to get individually and is not contained in VS by default? Because I can't find a way to use it, but the MSDN has loads of documentation on it..
I believe you can compile and run most Java programs with Visual J++. J++ was Microsoft's attempt to extend and proprietize Java so that it would get locked to the Windows platform -- it was thankfully not very successful.
The only downside is that you won't be running the latest and greatest Java release, so you might have to deal with bugs or deprecated classes. Most of the code we'll write here, however, is simple enough that it should run without problems for you.
- Warren
Thanks, I'll try to get it to run.. Or try to get someone to download the java SDK for me.. If I learn something, I may as well learn it the right way.. :)
... it's not all that well-organized ...I would say that it's well targetted. :wink:
... it's ... somewhat rushed!Brief and to the point, I think you mean. :wink:
I tried to invoke the make.bat file, but I got errors. I have attached a zip file that contains all contents of the c:\class folder.
I put the most recent code (the stuff that we're currently discussing) into the lesson2.java file. Then I double clicked on the make.bat file and the command window came up. After a few seconds, some lines appeared that said some errors. I have included everything from this command window output (as verbatim as possible) in the lesson2_errors.txt file.
Here's what I think I understand:
- The programmer (me) can arbitrarily use most combinations of letters (strings; is there a term for the smallest part of code that is still code?) as variables in the source code. The frame in the source code is one such example.
- There are some combinations of letters that the compiler recognizes for a specific purpose. The JFrame in the source code is one such example.
- Most of the combinations of letters in the source code that the compiler recognizes for a specific purpose require the programmer to alert the compiler's attention by declaring the import lines. If the import lines were not included, then the compiler would not recognize combinations of letters such as JFrame, and so such combinations of letters would also be arbitrary like frame.
- I suppose that learning the combinations of letters and the necessary imported classes that the compiler recognizes will just come with time/experience. Is there a book or (preferably) an online resource that lists these compiler recognized things?
Here's what I still need clarified:
- I don't see any kind of algorithmic "flow" in the source code; I don't know what else to call it. In Q-BASIC, FORTRAN, and Matlab, there is an algorithmic flow that I recognize. I can see how source code written in one of these languages will work by following it through its algorithm. In this java code, I don't see any commands or algorithmic structure; it just looks like a bunch of random lines of code. Is this just because it is such a simple program? Even when I looked at the source code for some of the demos it seemed like the same situation. It seems that the java source code is almost like lecture notes whereas the programming I'm used to is more like instructions for putting together a model airplane. Don't computers need instructions? Do I need to start thinking differently about programming? Is this what you meant by object oriented programming?
- Test is a class, and JFrame is a class, but JFrame is inside Test (by inside, I mean that it follows the openning curly bracket after the class declaration but preceeds the next closing curly bracket). Is this like nesting?
- Is the line of the source code protected JFrame frame; like declaring a variable to be used named frame that is of the data type JFrame and that is protected from something?
- I still don't understand what you mean by a Test object being created. You say that the constructor is called automatically when the Test object is created, but then why do you have to type the constructor? Does typing public class Test { ... not constitute creating a Test object?
- Is the syntax A.B().C(some stuff) generally useful, or is it very specific to the JFrame class? This syntax seems to imply an operation of some kind. What is the function of the .B() in this construct? B() and C() seem to resemble mathematical functions of variables. Is there some relationship/significance to this?
- In the main class, you say we're going to create a Test object, but I thought we had already created one at the beginning of the source code.
Now that I have gone through all of these questions, I think I am actually starting to see the resolutions to these issues. I would still appreciate your comments, though.
I tried to invoke the make.bat file, but I got errors... I put the most recent code (the stuff that we're currently discussing) into the lesson2.java file.
A file called lesson2.java must contain a class called lesson2. If the class inside is called Test, the file must be called Test.java. The names must be consistent.
- The programmer (me) can arbitrarily use most combinations of letters (strings; is there a term for the smallest part of code that is still code?) as variables in the source code. The frame in the source code is one such example.
Yes, variable names and method names are arbitrary combinations of alphanumeric characters and some special characters like the underscore. They also cannot begin with a number, only a letter. People have various conventions for style, and prefer names written in the style of loopCounter to other possibilities like loop_counter and LOOPCOUNTER.
The compiler actually recognizes things like variable and method names based on their position in the code; for example, the keyword "class" is a reserved word in the Java language; you cannot use it for your own variable names. Whenever the compiler sees the word "class," it expects a properly-formatted class name (made up by the programmer) to follow it.
There are some combinations of letters that the compiler recognizes for a specific purpose. The JFrame in the source code is one such example.
Yes, there some special words that are used to define structures; these words are called reserved words. A non-exhaustive list includes new, class, public, private, protected, if, while, for, continue, break, do, and so on.
Other words like JFrame are not actually built into the compiler; they are classes written by other people. When you use the word JFrame to indicate the type of a variable (again, the compiler knows it's used as a variable type by its context in the code), the compiler goes out and looks for a class called JFrame.
Most of the combinations of letters in the source code that the compiler recognizes for a specific purpose require the programmer to alert the compiler's attention by declaring the import lines. If the import lines were not included, then the compiler would not recognize combinations of letters such as JFrame, and so such combinations of letters would also be arbitrary like frame.
That is correct; but please note the distinction between words the compiler recognizes internally (like class and for and if), versus words the compiler used to reference other code (like JFrame).
I suppose that learning the combinations of letters and the necessary imported classes that the compiler recognizes will just come with time/experience. Is there a book or (preferably) an online resource that lists these compiler recognized things?
The Java environment provides a wealth of classes that you can use to build your applications; JFrame is just one. The entire API (application program interface) can be viewed here:
http://java.sun.com/j2se/1.4.2/docs/api/
Look in the left-hand frame and view the entry for the JFrame class if you'd like. You might also want to check out some very useful and simple classes like Vector.
I don't see any kind of algorithmic "flow" in the source code; I don't know what else to call it. In Q-BASIC, FORTRAN, and Matlab, there is an algorithmic flow that I recognize.
There definitely still is flow control in Java; once execution enters the top of a method, for example, it runs through that method exactly as you're used to seeing it run in other languages. The flow control is complicated by object orientation, however; constructors are run whenever the "new" reserved word is used, for example. You'll get used to the flow control very quickly, don't worry. Once you know how it works, you'll think it's positively brilliant.
Test is a class, and JFrame is a class, but JFrame is inside Test (by inside, I mean that it follows the openning curly bracket after the class declaration but preceeds the next closing curly bracket). Is this like nesting?
I would not say that JFrame is inside Test. JFrame actually has it's own quite long source code file, called JFrame.java, buried deep in the JDK library. I would simply say that Test uses JFrame, by referencing it. This is how you build applications in Java; objects use other objects.
Is the line of the source code protected JFrame frame; like declaring a variable to be used named frame that is of the data type JFrame and that is protected from something?
Absolutely correct in every way. The variable is in fact protected from the outside world; only code within the Test class can modify it (I'm being a bit sloppy, but that's close enough). The reason people use protection is to enforce good programming habits. Think back to the ChessPiece class -- you wouldn't want any old code anywhere in the world to be able to just arbitrarily set the x and y coordinates to anything they want. Only certain x and y positions are allowed; (-1, 105) would not be a valid position. Instead of trying to make all the code in the entire world aware of those restrictions, you make the variables private, and write a move() method. The move method could verify that the given position is valid before updating the variables. This way, your ChessPiece class is protected from the blunders of other programmers -- or even your own blunders.
I still don't understand what you mean by a Test object being created. You say that the constructor is called automatically when the Test object is created, but then why do you have to type the constructor? Does typing public class Test { ... not constitute creating a Test object?
Typing "public class Test {" does not create an object. You've just written a class -- a blueprint for an object. To actually create an object of the Test class, you use the "new" keyword, like "new Test()". When the "new" keyword is actually executed -- when the program is run -- the memory is allocated and so on to actually create a Test object.
Consider that classes exist in source code, and objects exist in memory at run-time.
Is the syntax A.B().C(some stuff) generally useful, or is it very specific to the JFrame class? This syntax seems to imply an operation of some kind. What is the function of the .B() in this construct? B() and C() seem to resemble mathematical functions of variables. Is there some relationship/significance to this?
Right on target. The JFrame class has variables and methods (remember, that's all a class is -- a collection of variables and methods that operate upon them). Let's say you have two windows, though, not just one. Maybe one is called mainWindow, and the other is called toolPalette. If you want to make one of these windows visible, you have to specify which one to the compiler. You do so by writing one of the following two lines:
mainWindow.setVisible(true);
toolPalette.setVisible(true);
The . loosely translates into "member." When you write mainWindow.setVisible, you are referring to the setVisible member of the mainWindow object. Both mainWindow and toolPalette are of class JFrame.
In the main class, you say we're going to create a Test object, but I thought we had already created one at the beginning of the source code.
Nope, once again, the beginning of the source code defines the blueprint for an object -- a class. A class is a blueprint for an object. You still have to actually use the blueprint to make an object, and that mechanism is the "new" keyword. Think of the "new" keyword as a construction crew which uses a blueprint, which defines what a house is, to build a real house. You can write one blueprint, and the construction crew can go out and build lots of houses from the blueprint that all start identical. After their construction, however, they can be modified independently. One family can put a blue couch in their house, while another can choose a red one.
The JFrame class is a blueprint for a window; you can make lots of windows from that blueprint, and each one is independent. They can have different titles, different contents, and so on.
Let me know if anything is still confusing..
- Warren
turin,
I have indeed taught programming classes in the past; I'm glad you find my writing so helpful, even when it's not all that well-organized and somewhat rushed!
Perhaps, you should think about writing a book. I'd buy it.
chroot,
I think I'm starting to get it. It is so hard in the beginning (I hope just in the beginning).
So, when one writes a *.java file, the purpose is to create a class? Then after writing 18 thousand (give or take) *.java files, one writes an "umbrella" or "master" (or "main"?) *.java file that takes advantage of the fact that most of the code work has been taken care of by the "sub" files by importing them and simply "calling" or "instantiating" (or "creating"?) them?
When you say that JFrame has its own file called JFrame.java, do you mean JFrame.class? It seems like the extension "java" indicates waiting to be complied (or source code) and the extension "class" indicates compiled code (or object code).
I'll probably try to play with lesson2 tonight (Fri night, I'm such a nerd).
Yes, you've basically got it... you write a bunch of classes, stick each in its own .java file, and compile them. Then you have one top-level class, which contains a special method called "main," that is the entry point to your entire program. The main method would then go and create whatever objects are used in the program, and so on.
And there was once a JFrame.java file somewhere, that someone wrote. If your JDK distribution includes the java source files, then you actually have a copy of it. If your JDK distribution did not come with the source, then you only have the JFrame.class file, which was compiled from the JFrame.java source code. Keep in mind that Java uses .jar files, basically the same as .zip files, to store large numbers of classes in an efficient way. There is probably a "rt.jar" file somewhere in your JDK directory. It stands for "runtime," and contains all of the classes like JFrame.class. Feel free to open the rt.jar file up with WinZip and look at what's inside.
- Warren
One thing that I forgot to ask about:
The main program imports all of the other subprograms that are written, but, for instance, JFrame.class is not in the c:\class directory. I'm assuming that I need to put it there? In general, do I need to put all of the supporting *.class files together or specify a path in the main program? How does that part work?
No, the java.exe program has an envrionment variable called CLASSPATH that includes all the locations where JFrame.class is likely to live. When your program references JFrame, the runtime environment scans the CLASSPATH variable and finds the appropriate code. Unless you've changed the CLASSPATH variable somehow, you don't need to worry about finding it yourself. Just let the runtime environment find it.
- Warren
I'm beginning to think that java is not what I want. I want to write programs that I can give to people to run on their computers. I don't want to have to give them an entire 50Meg java package.
Incidently, I got the lesson2 window to work. What's next? Here are some other things that I thought of besides animation:
- write a screen saver
- make a font for MS Word
- general file manipulation such as automatically moving/altering text in a *.txt file
Java is not a suitable language for either making a screensaver or a font.
And yes, your users will need to have a Java runtime environment installed in order to run your Java programs. If I'm not mistaken, all versions of Windows from 98 on include one. It may be out of date, however, so you'd need to write your code to the lowest-common-denominator API.
You can also write your programs as applets and let the user run them within a web browser. Web browsers typically have up-to-date runtime environments, but getting around browser security can be a pain. If you want to manipulate the user's hard drive, for example, it will be tough to do from an applet -- web browsers try to keep applets from doing exactly those kinds of things.
- Warren
OK. So, back to the animation applet. Lesson3 ...
Are the lines
import java.awt.*;
and
import javax.swing.*;
analogous to "#include" preprocessor directives in c/c++ (although it looks like in Java they are actually compiled along with the rest of the commands)?
What's special about the "toplevel class"? Is it simply that main() resides there? What considerations are there as to what else does or does not belong in that file?
In "main(String[] argv)" is the argument required by Java syntax even though no command line parameters are being used by this program? I tried it with just "main(){" and it seemed to compile OK but it gave an error when i tried to run it?
And finally...
do you plan to continue this thread?
Thanks Warren.
More questions:
where can I find a class that contains lines, arrows and circles?
what must be done to place a java program on a web page so it can be executed on-line?
(I'd like to try translating an animation that I wrote from c++ to java.)
master_coda
Jun12-04, 10:56 PM
And yes, your users will need to have a Java runtime environment installed in order to run your Java programs. If I'm not mistaken, all versions of Windows from 98 on include one. It may be out of date, however, so you'd need to write your code to the lowest-common-denominator API.
You can't really expect a Java runtime to be installed on any Windows machine. A lot of them have it installed, but a lot of them don't. Because of the legal wrangling between Microsoft and Sun, there have been long periods of time where Microsoft wasn't distributing the runtime along with Windows.
True, but I suspect that most people do have it anyway. The jre pretty much begs to be installed as soon as a web page containing an applet is loaded, and all it takes for most people to install sun's plugin is a couple of clicks, right?
master_coda
Jun12-04, 11:29 PM
True, but I suspect that most people do have it anyway. The jre pretty much begs to be installed as soon as a web page containing an applet is loaded, and all it takes for most people to install sun's plugin is a couple of clicks, right?
Actually, that doesn't happen anymore either. On Windows XP with no Java installed, if you go to a web page with an applet you'll just get nothing.
Depending on the version of Windows and the browser you're using, you may already have the runtime installed, or it may be really easy to install it, or you may just be left wondering why certain web pages don't work on your computer. And even when the runtime is installed, it's anybodys guess which version it is.
What's your point? Don't bother writing applets anymore? (Or in my case, don't bother learning how in the first place?)
The import statements just make it easier to type the names of classes by importing packages of classes into the default namespace. Thus, after importing javax.swing.JFrame, you can just call it JFrame. In C/C++, the #include directive actually inserts a file into the current file. That's not true in Java.
The toplevel class contains a main method. Perhaps "toplevel class" is not an official term for it, but it gets the job done. The toplevel class contains the entry point of the program.
And yes, the (String argv[]) is indeed required. If you leave out the arguments, you get a different method, still perfectly valid, but without any arguments. The Java runtime environment is looking for one with arguments.
- Warren
master_coda
Jun13-04, 11:46 AM
What's your point? Don't bother writing applets anymore? (Or in my case, don't bother learning how in the first place?)
No, of course not. Lots of great languages require a runtime to be distributed with programs written in them. It's just that Warren said that any version of Windows >= Win98 included a Java runtime, and I wanted to point out that you can't assume that.
If the fact that people may have to download a large runtime to use your program is a problem, then don't use Java to write that program. But there are lots of times when that isn't problem - so you can use Java then.
Normally I wouldn't just jump into a thread like this. But someone specifically mentioned that downloading a large runtime might be a problem, and I just wanted to give them all the facts.
musky_ox
Sep9-04, 10:57 PM
I have a question. What type of attitude should someone go into this with? I tried to learn java before, and i just got too bored of it. I found that i could never get a program to actually work because the debugger was too general. Any suggestions?
A good programmer doesn't need a debugger. And no, I'm really not being condescending -- it's true.
What exactly were you having trouble with?
- Warren
TenaliRaman
Sep11-04, 02:31 AM
And chroot is sooo right!
Usually the best way to debug is by placing checkpoints.Checkpoints are nothing but placing print statements at some places in the program and see if the program behaves the way we want to.....
In java, u can use System.out.println() to print values to the console.
A very useful function in c has always been getch() , so that the execution can be stopped at some point and the values can be carefully monitored...
Unfortunately there is not an equivalent in Java, but u can always make one ....
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class tri
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
try
{
i=br.read();
}
catch(Exception e){}
}
}
-- AI
Dr-NiKoN
Sep16-04, 04:42 PM
A good programmer doesn't need a debugger. And no, I'm really not being condescending -- it's true.
Strange statement.
Given some C code that's a couple of thousand lines that compiles fine without any errors at all, yet still gets a segmentation fault at run-time.
What would you do? How would you find that "of by 1" bounds error in some char*? Or that non null-terminated string you are expecting to be null terminated?
Using printf()-statements to check your code is fine, but are you sure you are handling all possible scenarios?
I'd say a debugger is a pretty important and powerfull tool for a programmer.
It's a matter of philosophy, I suppose. I tend to use a variant of cleanroom software engineering techniques, and have not actually written an off-by-one error or an array bounds error in many years. I would actually be quite happy to accept your challenge in regards to a 1kloc piece of code that segfaults. In fact, I would even be willing to bet money on my ability to find the problem in just a few minutes.
I consider off-by-one errors and array bounds errors to be, well.... novice mistakes. A debugger can certainly help a new programmer catch these kinds of mistakes, but, as the programmer gains experience, the debugger really just becomes less and less useful.
Once you throw threads and asynchronous data access into things, debuggers really become just about useless. The only way to write zero-defect code is to truly understand the code as you write it, and that takes experience.
- Warren
Dr-NiKoN
Sep16-04, 04:49 PM
A very useful function in c has always been getch() , so that the execution can be stopped at some point and the values can be carefully monitored...
Checking the backtrace is usually a lot faster. You can only guess where the problems are happening, the backtrace tells you where.
I'd say it would be far more superior just using breakpoints in your debugger and checking variables from there. As opposed to opening your file and commenting/uncommenting a debug-line somewhere in your source-code, recompiling and running again.
Dr-NiKoN
Sep16-04, 05:01 PM
I consider off-by-one errors and array bounds errors to be, well.... novice mistakes.
They are done by professional programmers all the time. We are only humans.
I'm really not talking about ability here. Very few people will be able to write something huge that just compiles and works perfectly straight away.
It's more about finding the error or how to debug your code.
I'd say a debugger is far superior to any "insert various print-statements in your code" variants.
Once you throw threads and asynchronous data access into things, debuggers really become just about useless
The more complex code, the more complex datastructures etc. the more complex debugging becomes. Using a debugger with threaded code can tell you what thread is causing problems. I don't understand why this would be useless.
I'd actually say it the other way around:
Using a debugger when you are learning programming is dumb. It has only negative effects on your learning experience, but once you get more experienced a debugger is IMO a good thing.
They are done by professional programmers all the time. We are only humans.
All programmers make mistakes. Few truly professional programmers make the same mistakes that students would make. The type of mistakes a programmer makes is certainly related to his/her experience. The effectiveness of a debugger is related to the type of errors being made, and thus is also related to the programmers experience.
I'm really not talking about ability here. Very few people will be able to write something huge that just compiles and works perfectly straight away.
I never said that. I said that experienced programmers don't make the kind of mistakes that debuggers are good at exposing.
I'd say a debugger is far superior to any "insert various print-statements in your code" variants.
Once again, it's a matter of philosophy. Many experienced programmers, myself included, think quite poorly of overuse of a debugger.
The more complex code, the more complex datastructures etc. the more complex debugging becomes. Using a debugger with threaded code can tell you what thread is causing problems. I don't understand why this would be useless.
What if the problem does not exist in one thread, but exists in the interdependence or cooperation of more than one thread?
Using a debugger when you are learning programming is dumb. It has only negative effects on your learning experience, but once you get more experienced a debugger is IMO a good thing.
You are welcome to your opinion. I have watched many students cling to the debugger far too long. Using a debugger forces a sort of "tunnel vision," in which students will make a change to their code, observe its behavior in the debugger, edit their code again, and so on. They freely add +1, for example, anytime they're off by one, without really considering the larger reason why their loop wasn't initialized properly in the first place. They place bandaids on open wounds without curing the underlying disease.
In my opinion, weaning oneself from a debugger is one of the first steps one can take to really being able to program. Learning strong, systematic software engineering techniques is the second.
- Warren
master_coda
Sep16-04, 07:02 PM
Debuggers tend to be a crutch; they make it easier to avoid thinking about the code you are trying to fix, just using trial-and-error instead. Of course, doing trial-and-error programming by inserting prints or logging everywhere isn't any better.
I do agree that a debugger usually isn't harmful to someone who's already a good programmer. But it usually isn't useful, either. Even if you have to fix a really big chunk of spagetti code written by someone else who isn't a good programmer, you're still better off simplifying the code first and then trying to fix it. And debuggers just aren't very useful for simple code.
Debuggers are only useful if you have code that you can't trace through in your head. This generally means that either the code jumps around alot, or has a large number of variables. Both of those things generally only occur in badly written code. Don't write such code yourself. If the code wasn't written by you, make it into good code before you try and debug it. If that is beyond your abilities, then you are not a good programmer.
Here's my first stab at Java. No fancy graphics, just a simple queue implemented as a linked list. It actually seems to work :approve: but I'd appreciate any constructive criticism you might offer.
In particular, I'm wondering about my implementation of Empty(). In C or C++ I'd never just "dump" the nodes the way I did here, but I get the impression that this is OK in Java. Yes?
Also, should my deQueue() method provide some protection against the user attempting to remove an object from an empty queue, or is the normal practice to leave that for the main program to deal with (as I did here)?
(It's homework, so please offer criticisms/suggestions, but don't rewrite it for me.)
Thanks.
Here's MyQueue.java:
// MyQueue.java
public class MyQueue {
MyNode first;
MyNode last;
int size;
public MyQueue() {
first = null;
last = null;
size = 0;
}
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
public void enQueue(Object o) {
MyNode nextNode = new MyNode(o);
if (isEmpty()) {
first = nextNode;
last = nextNode;
}
else {
last.next = nextNode;
last = nextNode;
}
size++;
}
public Object deQueue() {
MyNode temp = first;
if (size == 1) {
first = null;
last = null;
size --;
}
else if (size > 1) {
first = first.next;
size --;
}
return temp.data;
}
public void Empty() {
first = last = null;
size = 0;
}
}
class MyNode {
Object data;
MyNode next;
MyNode (Object o) {
data = o;
next = null;
}
}
and here's a test driver, testMyQueue.java:
// testMyQueue.java
// test driver for MyQueue class
class testMyQueue {
public static void main(String[] args) {
MyQueue q = new MyQueue();
Integer n;
for(int j=0; j<4; j++) {
System.out.println("\nTesting five entries to the queue.");
for(int i=0; i<5; i++) {
n = new Integer(2*i*j);
q.enQueue(n);
}
while(!q.isEmpty()){
n = (Integer) q.deQueue();
System.out.println(n);
}
}
q.Empty();
if(q.isEmpty()) {
System.out.println("The queue is now empty.\n");
System.out.println("One last trial...");
}
for(int i=0; i<5; i++) {
n = new Integer(10*i);
q.enQueue(n);
}
while(!q.isEmpty()){
n = (Integer) q.deQueue();
System.out.println(n);
}
System.out.println("Goodbye.");
}
}
Here's my first stab at Java. No fancy graphics, just a simple queue implemented as a linked list. It actually seems to work :approve: but I'd appreciate any constructive criticism you might offer.
For a first stab it looks pretty good!
No,you don't need to concern yourself with deallocating memory. This is a job for the garbage collector.
A few things:
1. Trying to dequeue an element from an empty queue should throw an exception. This is the usual practice in Java and it is good practice IMO. The client deals with the exception at whatever level it wants.
2. The Java coding convention is to use camel case names for methods (i.e. use "empty" instead of "Empty").
3. Using a sentinel node would simplify a lot of code. For example the empty check becomes "return first == last" and the enque function doesn't need case-by-case analysis. If you don't need a getSize() method then you could discard the size field.
4. The Node class should probably be nested in the Queue class. It can safely be made private. The user shouldn't know or concern himself with such details.
5. The member variables first, last and size should be private.
I hope that helps.
regards,
radu
Thanks for the suggestions, Radu. I vaguely remember being briefly introduced to sentinels in my Data Structures class a couple of years ago, but I've never used one since then. I have improvised based on what I think a sentinel should do, but I'm not sure it's what you had in mind, unless you're using first as a reference to the sentinel, so please let me know if there's a better (or more generally accepted) way of implementing it.
Regarding the exception class, I haven't found any explanation of the purpose of the line super();Can you shed any light on that?
Also, I see that the "String s" exception constructor is optional, and I can't figure out what purpose it would serve. What can you tell me about that?
Here's my revised code.
MyQueue.java:
public class MyQueue {
private class MyNode {
Object data;
MyNode next;
MyNode () { // constructor for sentinel node
data = null;
next = null;
}
MyNode (Object o) { // constructor for other nodes
data = o;
next = null;
}
};
private MyNode sentinel, last;
public MyQueue() {
last = sentinel = new MyNode();
}
public boolean isEmpty() {
return sentinel == last;
}
public void enQueue(Object o) {
MyNode nextNode = new MyNode(o);
last.next = nextNode;
last = nextNode;
}
public Object deQueue() throws EmptyQueueException {
if (last == sentinel)
throw new EmptyQueueException();
MyNode temp = sentinel.next;
sentinel.next = temp.next;
if (last == temp)
last = sentinel;
return temp.data;
}
public void empty() {
last = sentinel;
last.next = null;
}
}
EmptyQueueException.java:
public class EmptyQueueException extends java.lang.Exception {
EmptyQueueException() {
super();
}
EmptyQueueException(String s) {
super(s);
}
}
testMyQueue.java
class testMyQueue {
public static void main(String[] args) {
MyQueue q = new MyQueue();
Integer n;
for(int j=0; j<4; j++) {
System.out.println("\nTesting five entries to the queue.");
for(int i=0; i<5; i++) {
n = new Integer(2*i*j);
q.enQueue(n);
}
while(true){
try {
n = (Integer) q.deQueue();
System.out.println(n);
} catch (EmptyQueueException e) {
System.out.println("Queue is empty");
break;
}
}
}
for(int i=0; i<5; i++) {
n = new Integer(2*i);
q.enQueue(n);
}
q.empty();
if(q.isEmpty()) {
System.out.println("The queue is now empty.\n");
System.out.println("One last trial...");
}
for(int i=0; i<5; i++) {
n = new Integer(10*i);
q.enQueue(n);
}
while(!q.isEmpty()){
try {
n = (Integer) q.deQueue();
System.out.println(n);
} catch (EmptyQueueException e) {
System.out.println("We should never get caught here.");
}
}
System.out.println("Goodbye.");
}
}
The line "super()" simply invokes the superclass constructor. In this case, it runs the java.lang.Exception constuctor. It is not necessary to explicitly call the superclass constructor, as it will be called automatically anyway, but it's never a bad idea.
The constructor that takes a String argument allows you to provide a message that might be helpful to the user of your class. In this case, the name of the exception is self-explanatory, so the String argument is not very useful. In some cases though, it's nice to provide a bit more detail as to exactly why the exception was thrown.
- Warren
I have improvised based on what I think a sentinel should do, but I'm not sure it's what you had in mind,
That's what I had in mind :) Here is an article "on sentinels":
http://www.topcoder.com/?&t=features&c=feat_090104
A nice discussion about implementing lists can be found here:
http://tinyurl.com/53tpe
Look especially at lecture notes 4, 5, and 6. If I remember correctly it includes the sentinel stuff.
public Object deQueue() throws EmptyQueueException {
if (last == sentinel)
throw new EmptyQueueException();
MyNode temp = sentinel.next;
sentinel.next = temp.next;
if (last == temp)
last = sentinel;
return temp.data;
}
You can replace the second if with "sentinel = temp".
regards,
radu
Originally posted by rgrig
You can replace the second if with "sentinel = temp".
Thanks again. Actually, if I make that change, I can also eliminate the line (sentinel.next = temp.next;) above that second if so now deQueue is just:
public Object deQueue() throws EmptyQueueException {
if (last == sentinel)
throw new EmptyQueueException();
MyNode temp = sentinel.next;
sentinel = temp;
return temp.data;
}
Very elegant!
Thanks also to Warren for explaining the exception constructors.
I'm working on a complex number class for homework. What I have so far seems to work correctly, but for some of the results
System.out.print()
gives unexpected decimal representations, such as
5.6i + 2.8i = 8.399999999999999i
yet others are "normal", such as
5.6i - 2.8i = 2.8i
It doesn't seem to be restricted to specific operations; for example when I put different values in the test program, I got
4.0i - 2.8i = 1.2000000000000002i
Is this just a normal consequence of using doubles?
If so, how should I change my
System.out.print()
commands to correct this?
// Complex.java
// implements a complex number type
public class Complex {
public Complex() {
_real = 0.0;
_imag = 0.0;
}
public Complex (double re, double im) {
_real = re;
_imag = im;
}
public static Complex add (Complex x, Complex y) {
return new Complex(x._real + y._real, x._imag + y._imag);
}
public static Complex subt (Complex x, Complex y) {
return new Complex(x._real - y._real, x._imag - y._imag);
}
public static Complex mult (Complex x, Complex y) {
return new Complex(x._real * y._real, x._imag * y._imag);
}
static public Complex div (Complex x, Complex y) {
return new Complex(x._real / y._real, x._imag / y._imag);
}
public static double real(Complex x) {
return x._real;
}
public static double imag(Complex x) {
return x._imag;
}
public double real () {
return _real;
}
public double imag () {
return _imag;
}
private double _real, _imag;
}
with this test driver:
// TestComplex.java
// test driver for Complex class
class TestComplex {
public static void main (String[] args) {
double re,im;
Complex c1, c2, c3, result;
c1 = new Complex();
c2 = new Complex();
c3 = new Complex();
System.out.println("Testing default constructor with instance methods:");
System.out.println("c1 = " + c1.real() + " + " + c1.imag() + "i");
System.out.println("Testing default constructor with static methods:");
System.out.println("c1 = " + Complex.real(c1) + " + " + Complex.imag(c1) + "i");
System.out.println("Testing set-value constructor:");
c1 = new Complex(6.4,5.6);
c2 = new Complex(2.0,2.8);
System.out.println("c1 = " + c1.real() + " + " + c1.imag() + "i");
System.out.println("c2 = " + c2.real() + " + " + c2.imag() + "i");
System.out.println("\nTesting addition:");
result = Complex.add(c1,c2);
System.out.print("(" + c1.real() + " + " + c1.imag() + "i)");
System.out.print(" + (" + c2.real() + " + " + c2.imag() + "i)");
System.out.println(" = (" + result.real() + " + " + result.imag() + "i)");
System.out.println("\nTesting subtraction:");
result = Complex.subt(c1,c2);
System.out.print("(" +c1.real() + " + " + c1.imag() + "i)");
System.out.print(" - (" + c2.real() + " + " + c2.imag() + "i)");
System.out.println(" = (" + result.real() + " + " + result.imag() + "i)");
System.out.println("\nTesting multiplication:");
result = Complex.mult(c1,c2);
System.out.print("(" +c1.real() + " + " + c1.imag() + "i)");
System.out.print(" * (" + c2.real() + " + " + c2.imag() + "i)");
System.out.println(" = (" + result.real() + " + " + result.imag() + "i)");
System.out.println("\nTesting division:");
result = Complex.div(c1,c2);
System.out.print("(" +c1.real() + " + " + c1.imag() + "i)");
System.out.print(" / (" + c2.real() + " + " + c2.imag() + "i)");
System.out.println(" = (" + result.real() + " + " + result.imag() + "i)");
System.out.println("\nTesting division by zero:");
result = Complex.div(c1,c3);
System.out.print("(" +c1.real() + " + " + c1.imag() + "i)");
System.out.print(" / (" + c2.real() + " + " + c2.imag() + "i)");
System.out.println(" = (" + result.real() + " + " + result.imag() + "i)");
System.out.println("\nFinished.");
}
}
Use this:
NumberFormat numberFormatter = new NumberFormat();
numberFormatter.setMaximumFractionDigits(2);
System.out.println(....numberFormatter.format(c1.r eal())....);
- Warren
courtrigrad
Sep25-04, 07:21 AM
Hello.
I have a java program where there is a falling cube. I am trying to make the cube fall, then bounce back up and fall again forever. I know i have to use a for loop.Can someone please guide me as to what to do?
Thanks!
Does a thread just "go away" when it reaches the end of its run() method, or am I supposed to do something to clean up?
ghome,
When a Thread's run() method returns, it no longer occupies any CPU resources. It will continue to take up some modest memory resources until there are no more references to it. Then it will be garbage-collected and its memory freed.
- Warren
Ok, this place is as good as any to post and try and get an answer to this. This program is supposed to read a keyboard input of an integer 1-100 and output the change from a dollar that you get back.
For example: 27
2 Quarters
2 Dimes
3 Pennies
It won't work and I'm killing myself over this. This error comes up when compiling:
java:33: cannot resolve symbol variable Keyboard location: class evan3 amount = Keyboard.readInt ();
Here is the program:
public class evan3
{
public static void main (String[] args)
{
final int DOLLAR = 100;
final int QUARTER = 25;
final int DIME = 10;
final int NICKEL = 5;
final int PENNY = 1;
int amount = 0;
int change = 0;
int numQuarters = 0;
int remQuarters = 0;
int numDimes = 0;
int remDimes = 0;
int numNickels = 0;
int remNickels = 0;
int numPennies = 0;
while (true) // infinite loop
{
System.out.print ("Enter the purchase amount [1-100], enter 0 to exit : ");
amount = Keyboard.readInt ();
if (amount < 0 || amount > 100)
{
System.out.println ("Amount not in range [0 - 100]");
continue;
}
if (amount == 0)
{
System.out.println ("Bye");
break;
}
change = DOLLAR - amount;
numQuarters = change / QUARTER;
remQuarters = change % QUARTER;
numDimes = remQuarters / DIME;
remDimes = remQuarters % DIME;
numNickels = remDimes / NICKEL;
remNickels = remDimes % NICKEL;
numPennies = remNickels / PENNY;
if (numQuarters >1 || numQuarters == 0)
System.out.println ("Quarters");
else
System.out.println ("Quarter");
if (numDimes >1 || numDimes == 0)
System.out.println ("Dimes");
else
System.out.println ("Dime");
if (numNickels >1 || numNickels == 0)
System.out.println ("Nickels");
else
System.out.println ("Quarter");
if (numPennies >1 || numPennies == 0)
System.out.println ("Pennies");
else
System.out.println ("Penny");
} // while
} // main
} // Lab3
Any help? I'm missing something here.
Well, you're missing that Keyboard class/object you referenced. I have no idea where you heard of a Keyboard class -- perhaps it's something your instructor made up for you to use?
You can always just wrap the System.in stream in a DataInputStream and use its readInt method:
int amount = new DataInputStream(System.in).readInt();
- Warren
The keyboard class file was something the teacher told us to put in. I downloaded the keyboard class into the same folder where the java file is located and it is supposed to work but it isn't working.
:confused:
Does the Keyboard.class file have to exist within a package? Do you need to use the import statement to import it? Can you provide an example of a program which successfully uses this class?
- Warren
We just did a coin java program like that in my computer science class.
Ok, so it turns out that error message had to with the capitalization of the title of the keyboard.java document.
I really suck at java.
Ok so now the output just lists the denominations: Quarters, Dimes, Nickels, Pennies. How do I get the appropriate numbers to show up? Does it have something to do with the coding around this part...
change = DOLLAR - amount;
numQuarters = change / QUARTER;
remQuarters = change % QUARTER;
numDimes = remQuarters / DIME;
remDimes = remQuarters % DIME;
numNickels = remDimes / NICKEL;
remNickels = remDimes % NICKEL;
numPennies = remNickels / PENNY;
Do I need brackets or println's or something? Some sort of extra coding to get it to work?
How did you manage to get this done Entropy? Any pointers?
Edit: Fixed one problem. Getting there.... :yuck:
For my first foray into threads, I wrote a readers/writers (shared resource) simulation. The main() method has an int variable "clock", and it just keeps looping and incrementing clock on each loop. While it loops it creates reader and writer threads, according to a randomly generated schedule; each reader & each writer is a separate thread, and when each one is created it is passed a parameter "duration" telling it the length of time it should be active.
I want each reader or writer thread to release the shared resource after it has been active for its alloted amount of time, so in each constructor I pass "clock" as a parameter, and I set a member int variable of the thread class = to that parameter. I thought that would work since I understood that in Java parameters are passed by reference. But it's not working: the readerthreads and writerthreads are not seeing the updating of the clock value that's occurring in main(). Instead each of those threads just sees a constant clock value -- the value that clock had when the thread was created.
How can I enable the child threads to see the updating of a variable that's occuring in the parent (main) thread?
Prometheus
Oct7-04, 10:39 PM
The main() method has an int variable "clock",
I understood that in Java parameters are passed by reference.
Objects are passed by reference. ints are not.
How can I enable the child threads to see the updating of a variable that's occuring in the parent (main) thread?
There are numerous ways, some more elegant than others. A simple way is not to pass the value at all. The child threads can access the clock value by ClassName.clock, assuming that the clock variable was declared:
public static int clock;
ek:
you only asked it to print the words:
for example,
System.out.println ("Quarters");
just says to print exactly what's inside the quotes, in this case the word Quarters.
What you want is
System.out.println (String.valueOf(numQuarters) + " Quarters");
and so on...
(String.valueOf(int i) is a static method of the String class that converts an int to a string.)
Prometheus
Oct7-04, 10:43 PM
System.out.println (String.valueOf(numQuarters) + " Quarters");
I usually write this System.out.println (numQuarters + " Quarters");
originally posted by prometheus:
There are numerous ways, some more elegant than others. A simple way is not to pass the value at all. The child threads can access the clock value by ClassName.clock, assuming that the clock variable was declared:
public static int clock;
Does it need to be static? Clock is declared in the main function of the project.
Originally posted by Prometheus:
I usually write this System.out.println (numQuarters + " Quarters");
Thanks. I didn't realize println() was that smart. :smile:
Prometheus
Oct7-04, 11:00 PM
Does it need to be static? Clock is declared in the main function of the project.
You mean the main method, not main function.
No, of course not. I said that there are many solutions. This is not a solution that I would use.
However, you are writing your code inside the main method. I suspect, although I may be wrong, that you are new to Java. Otherwise, why write your code in the main method? Since you are writing your code in the main method, you have no objects. By the way, I would declare this variable outside of the main method, at class scope.
TYpically, if I have a variable that I want other objects to see, I pass in the constructor a this reference. The constructed object can then call an accessor method in the creating object to determine the value of the variable. In order to do this, however, the creator must be an object. Your program in the main method does not qualify. Unless you have good reason, I recommend that you do not write Java programs inside of the main method.
Yes I am definitely new to Java: I wrote hello, world in Java 2 weeks ago for the 1st time.
In this case my main method is just a test driver that instantiates the various ReaderThread and WriterThread objects, and "ticks" the clock. Everything else is in 5 separate class files:
ReaderThread
WriterThread
ReaderCounter
WriterCounter
BinarySemaphore
I tried changing the declaration of clock but I keep getting an "illegal start of expression" error, whether I call it public static int clock; or public int clock; or static int clock;
It only lets me do int clock;
Why?
edit: Got it. I had to move the declaration outside of the main method.
Thanks Prometheus. It looks like it's running correctly now, but it'll take a while to analyze all the starting and finishing messages from the threads to make sure they're all behaving nicely.
Prometheus
Oct7-04, 11:34 PM
I tried changing the declaration of clock but I keep getting an "illegal start of expression" error, whether I call it public static int clock; or public int clock; or static int clock;
It only lets me do int clock;
Why?
edit: Got it. I had to move the declaration outside of the main method.
The main method is static, so that all variables declared inside of it are static by context: hence, static is invalid. The main method is a method, so that all variables inside of it are local; hence, public is invalid.
If you have a question, it helps to post your code if it is not too large.
I believe it's now working the way I intended, but if you don't mind wading through it, I'd welcome any comments, criticisms or suggestions you may offer. Anyway, thanks for your help.
// test driver for readers/writers problem
// There can be multiple readers, or a single writer, active at any time.
// This solution gives priority to writers: active readers are allowed to
// finish, but no new readers can start if there is a waiting writer.
import java.util.Random;
import java.util.Arrays;
public class testReadWrite{
public static int clock;
public static void main(String[] args){
final int trial_len = 200;
final int num_readers = 10;
final int num_writers = 10;
final int max_read_time = 10;
final int max_write_time = 4;
Random randnum = new Random();
ReaderCounter rc = new ReaderCounter();
WriterCounter wc = new WriterCounter();
BinarySemaphore writing = new BinarySemaphore();
ReaderThread r;
WriterThread w;
// int clock; // used to count iterations of the while loop (below)
clock = 0;
String s = new String();
int[] read_arrive = new int[num_readers];
int[] read_len = new int [num_readers];
int[] write_arrive = new int [num_writers];
int[] write_len = new int [num_writers];
for (int i = 0; i < num_readers; i++){
read_arrive[i] = randnum.nextInt(100);
read_len[i] = randnum.nextInt(30) + 5; // don't want any 0 durations
}
for (int i = 0; i < num_writers; i++){
write_arrive[i] = randnum.nextInt(100);
write_len[i] = randnum.nextInt(5) + 5; // don't want any 0 durations
}
Arrays.sort(read_arrive);
Arrays.sort(write_arrive);
// next 10 lines are just for evaluating the results
for (int i = 0; i<num_readers; i++){
System.out.print("reader" + String.valueOf(i) + " ");
System.out.println("arr: " + String.valueOf(read_arrive[i]) + " len: "
+ String.valueOf(read_len[i]));
}
for (int i = 0; i<num_writers; i++){
System.out.print("writer" + String.valueOf(i) + " ");
System.out.println("arr: " + String.valueOf(write_arrive[i]) + " len: "
+ String.valueOf(write_len[i]));
}
while (clock<trial_len){
System.out.println("clock = " + String.valueOf(clock));
for (int i = 0; i < num_readers; i++){
if (read_arrive[i]==clock){
// form name of new reader
s = "reader";
s = s.concat(String.valueOf(i));
// create new reader, specifying its read duration
r = new ReaderThread(s,read_len[i],rc,wc,clock);
r.start();
}
}
for (int i = 0; i < num_writers; i++){
if (write_arrive[i]==clock){
// form name of new writer
s = "writer";
s = s.concat(String.valueOf(i));
// create new reader, specifying its read duration
w = new WriterThread(s,write_len[i],rc,wc,writing,clock);
w.start();
}
}
try{
Thread.sleep(0,50);
} catch(InterruptedException e){
}
clock++;
}
}
}
// writer class for readers/writers problem
// test driver must instantiate ReaderCounter rc, WriterCounter wc
// BinarySemaphore writing, int clock
public class WriterThread extends Thread{
public WriterThread(String s, int d, ReaderCounter rctr, WriterCounter wctr,
BinarySemaphore bs, int clk){
super(s);
name = s;
duration = d;
rc = rctr;
wc = wctr;
writing = bs;
clock = clk;
System.out.println(s + "created.");
}
public void run(){
// reversed the order of the following 2 lines
wc.addWriter(); // add to count of waiting writers
rc.writerPass(); // check ReaderCounter for any active readers
writing.acquire(); // wait for semaphore to start writing
finish_time = testReadWrite.clock + duration;
while(finish_time > testReadWrite.clock) // changed from <
{
try{
System.out.println(name + ": clock = " + testReadWrite.clock +
"; finish_time = " + finish_time);
sleep(0,10); // writer is writing
} catch(InterruptedException e){
}
}
writing.release(); // finished writing
wc.delWriter();
}
private String name;
private int clock;
private int duration;
private int finish_time;
private ReaderCounter rc;
private WriterCounter wc;
private BinarySemaphore writing;
}
// reader class for readers/writers problem
// test driver must instantiate ReaderCounter rc, WriterCounter wc
// BinarySemaphore writing, int clock
public class ReaderThread extends Thread{
public ReaderThread(String s, int d, ReaderCounter rctr,
WriterCounter wctr, int clk){
super(s);
name = s;
duration = d;
rc = rctr;
wc = wctr;
clock = clk;
System.out.println(s + "created.");
}
public void run(){
wc.readerPass(); // readers not allowed to start if a writer is waiting
rc.addReader(); // makes writers wait while any readers are reading
finish_time = testReadWrite.clock + duration;
while(finish_time > testReadWrite.clock) // changed from <
{
try{
System.out.println(name + ": clock = " + testReadWrite.clock +
"; finish_time = " + finish_time);
sleep(0,10); // reader is reading
} catch(InterruptedException e) {
}
}
rc.delReader(); // finished
}
private String name;
// duration and finish_time will be used by test driver to determine when
// this thread finishes reading
private int clock;
private int duration;
private int finish_time;
private ReaderCounter rc;
private WriterCounter wc;
}
// utility class for reader/writers problem
// test driver will instantiate one ReaderCounter named "rc"
public class ReaderCounter{
public ReaderCounter(){
count = 0;
}
// used by reader starting to read
public synchronized void addReader(){
count++;
System.out.println(Thread.currentThread().getName( ) + " starting to read.");
notifyAll(); //in case another reader tried to start at same time
}
// used by reader finished reading
public synchronized void delReader(){
count--;
System.out.println(Thread.currentThread().getName( ) + " finished reading.");
notifyAll(); //in case a writer is waiting
}
// used by writer wanting to write
public synchronized void writerPass(){
while(count > 0){
try{
wait();
} catch (InterruptedException e){
}
}
System.out.println(Thread.currentThread().getName( ) + " checking for active readers.");
}
// unsynchronized: used by main test loop to see when to terminate
public int getCount(){
return count;
}
private int count;
}
// utility class for reader/writers problem
// test driver will instantiate one WriterCounter named "wc"
public class WriterCounter{
public WriterCounter(){
count = 0;
}
// used by writer waiting to write
public synchronized void addWriter(){
count++;
System.out.println(Thread.currentThread().getName( ) + " added to WriterCounter.");
notifyAll(); //in case another writer is trying
}
// used by writer finished writing
public synchronized void delWriter(){
count--;
System.out.println(Thread.currentThread().getName( ) + " removed from WriterCounter.");
notifyAll(); //in case other writers or readers are waiting
}
// used by reader wanting to read
public synchronized void readerPass(){
while(count > 0){
try{
wait();
} catch (InterruptedException e){
}
}
}
// unsynchronized: used by main test loop to see when to terminate
public int getCount(){
return count;
}
private int count;
}
// semaphore class for reader/writers problem
public class BinarySemaphore{
public BinarySemaphore(){
value = 1;
}
public synchronized void acquire(){
while (value == 0){
try{
wait();
} catch(InterruptedException e){
}
}
value = 0;
System.out.println(Thread.currentThread().getName( ) + " now writing.");
}
public synchronized void release(){
System.out.println(Thread.currentThread().getName( ) + " finished writing.");
value = 1;
notifyAll();
}
private int value;
}
Thanks a lot guys, I really appreciate it. After the time I spent on this, it was pretty satisfying to finally get it to work.
Thanks for the help!
:biggrin:
Prometheus
Oct8-04, 12:12 AM
I believe it's now working the way I intended, but if you don't mind wading through it, I'd welcome any comments, criticisms or suggestions you may offer. Anyway, thanks for your help.
Looks pretty good for someone new to Java. I don't have my Java JVM on this machine to load and test it, so I won't comment on it absent a question.
Note that your String.valueOf() are not necessary, and I prefer to omit them.
This method is called automatically when a primitive is concatenated to a string.
Prometheus
Oct8-04, 12:38 PM
I believe it's now working the way I intended, but if you don't mind wading through it, I'd welcome any comments, criticisms or suggestions you may offer.
I noticed that your ReaderCounter and WriterCounter classes are 100% identical, except for slight differences in method names. I recommend that you just use the same class for both. If you were to have differences in behavior, an interface or an abstract superclass would be better than two classes that are basically identical. In this case, however, I see no difference in functionality at all.
Point well taken. Thanks again.
I'm supposed to write an applet to draw a chessboard using two nested "if" statements. How would I even go about starting this?
Something like attaching numerical values to each square and write "if int=even color black else color white"?
What would the other if statement be? How would you even get the chessboard to look like a chessboard?
This java class is getting to me. It's just getting harder and harder.
Any hints?
TenaliRaman
Oct14-04, 01:19 AM
the simplest way to draw a chessboard use
fillRect(int,int,int,int) along with setColor(Color)
choose any start position x,y
choose a neat size for the square as squareSize
run a for loop and change the x as x+squareSize
and at each x,y draw a square (change color as a mod 2 operation)
and once u have drawn 8 squares then change y as y+squareSize
Thus, draw Squares row wise till 8 rows .... and u have a chess board ...
-- AI
Ok this is what I got so far, it's pretty hopeless, I know.
How do I choose a start position?
How do I get the squares to start repeating? (using a for loop I'm guessing, but how)
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
public class Evan4 extends Applet
{
//stuff here
final int NUM_SQUARES = 64;
final int SQUARE_WIDTH = 30;
int x = 5;
int y = 5;
public void paint (Graphics g)
{
for (int count = 0; count < NUM_SQUARES; count++);
{g.setColor (Color.black);
g.fillRect(x,y,SQUARE_WIDTH,SQUARE_WIDTH);
x += SQUARE_WIDTH;
y += SQUARE_WIDTH;
}
}
}
TenaliRaman
Oct14-04, 10:06 AM
public final int INITIAL_X = /*somevalue*/
public final int INITIAL_Y = /*somevalue*/
for(x=INTIAL_X;x<INITIAL_X+SQUARE_WIDTH*8;x+=SQUARE_WIDTH)
for(y=INITIAL_Y;y<INITIAL_Y+SQUARE_WIDTH*8;y+=SQUARE_WIDTH)
{
/*draw rectangle here*/
}
-- AI
BTW, the notation:
for (int count = 0; count < NUM_SQUARES; count++);
is equivalent to this
for (int count = 0; count < NUM_SQUARES; count++)
;
and actually means an EMPTY for loop. Lose the semicolon.
- Warren
Ok, I got some help at school today, but it still won't draw properly. It's a problem inside the for loops. It isn't resetting itself to y=0 when the row reaches the LIMIT (8 squares). It just draws them consecutively. Why? How do I fix this?
import java.applet.Applet;
import java.awt.*;
public class Evan4 extends Applet
{
//variables and values
final int LIMIT = 8;
int x = 20;
int y = 20;
int height = 20;
int width = 20;
int ypos;
int xpos;
public void paint (Graphics g)
{
//colour of background
setBackground (Color.gray);
// initial box color
g.setColor (Color.white);
//loop for x
for (int count = 0; count < LIMIT; count++)
//y for loop
{
for (int county = 0; county < LIMIT; count++)
{
//x and y values changing
xpos = x+width*count;
ypos = y+height*county;
//if box is even count draw box black, else white
if ((count + county) % 2 ==0)
g.setColor (Color.black);
else
g.setColor (Color.white);
g.fillRect (xpos, ypos, width, height);
}
}
}
}
TenaliRaman
Oct14-04, 07:31 PM
You have made one small but highly annoying error ...
Look at this statement :-
for (int county = 0; county < LIMIT; count++)
Do u see something wrong here?
-- AI
You have made one small but highly annoying error ...
Look at this statement :-
for (int county = 0; county < LIMIT; count++)
Do u see something wrong here?
-- AI
No I don't. I suck at java.
:cry:
It just won't go back to the y origin and draw 8x8. That's pretty much the only problem. It just draws on one y value.
I'm missing something. And it's really making me mad. It's so frustrating.
No I don't. I suck at java.
:cry:
You are incrementing count in a loop that tests county.
- Warren
You are incrementing count in a loop that tests county.
- Warren
Awesome. Thanks.
Amazing that such a small error can screw you over so badly.
You guys are great.
Next time you have such an error, consider adding some print statements in strategic places to watch what your program is doing.
I have come across many instances in my career where one single character makes the difference between a perfect program and a disastrous one. Programming requires almost neurotic attention to detail.
- Warren
Ok, one last thing.
How would I turn my applet for drawing a chessboard into one that randomly produces chessboards at time intervals at random places on the page? With random colours to boot.
Alright so I gave it a try, but this code gets lots of compiling errors.
What is fundamentally wrong with this code? What's missing or in the wrong place? It says the if/else statement is screwed up as well.
Edit: I know some of it is off, it's cut/pasted. (like the black/white stuff)
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
;
public class Evan4c extends Applet
{
//variables and values
final int WIDTH = 20;
final int LENGTH = 20;
final int LIMIT = 8;
int x = 20;
int y = 20;
int height = 20;
int width = 20;
int ypos;
int xpos;
int n = 150; // wait n milliseconds
int w = (int) (Math.random () * 41);
public void paint (Graphics g)
{
//colour of background
setBackground (Color.cyan);
// initial box color
g.setColor (Color.white);
//loop for x
for (int count = 0; count < LIMIT; count++)
//y for loop
{
for (int county = 0; county < LIMIT; county ++)
{
//x and y values changing
xpos = x+width*count;
ypos = y+height*county;
//if box is even count draw box black, else white
if ((count + county) % 2 ==0)
Color c = new Color;
(int)(Math.random () * 256);); // red = 0..255
(int)(Math.random () * 256), // green = 0..255
(int)(Math.random () * 256)); // blue = 0..255
g.setColor (c);
else
Color c = new Color (
(int)(Math.random () * 256), // red = 0..255
(int)(Math.random () * 256), // green = 0..255
(int)(Math.random () * 256)); // blue = 0..255
g.setColor (c);
g.fillRect (xpos, ypos, width, height);
}
}
}
}
You forgot to use braces to wrap the two clauses in your if statement.
Try looking at your first "Color c = ..." statement.
But most importantly, I thought you were trying to draw black and white rectangles, but for both cases you're trying to draw a randomly colored rectangle.
Here's my error log, what's going on here?
C:\Documents and Settings\Evan\Desktop\Evan4c.java:47: '.class' expected
(int)(Math.random () * 256), // red = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:48: ')' expected
(int)(Math.random () * 256); // green = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:49: not a statement
(int)(Math.random () * 256); // blue = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:55: '.class' expected
(int)(Math.random () * 256), // red = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:57: ')' expected
(int)(Math.random () * 256); // blue = 0..255
Never mind. I figured it out.
Ok, I have a new problem.
This time I'm trying to make a program that prints all the prime factors of a given number and the 29 numbers one less than it. These numbers iare 432731 -> 432702.
So here is my program:
public class evan5ccc
{
/* the method tests whether a number is prime*/
public static boolean Primes(int input)
{
for (int x=2; x < input; x++)
if (input % x == 0)
return false;
return true;
}
/*
computes the smallest prime factor of the input number,
returns that number divided by its smallest prime factor
*/
public static int factor (int input)
{
if (input == 1)
return input;
else
{
for (int x=2; x <= input; x++)
if (input % x == 0)
{
System.out.print(" " + x );
return (input / x);
}
}
return 0;
}
public static void main(String args[])
{
int number; // number to be decomposed
for (number=432731; number > 432701; number--)
System.out.println("Prime factors of " + number + ":");
while (number != 1)
{
number = factor(number);
}
}
}
And here is the output:
Prime factors of 123456760:
Prime factors of 123456761:
Prime factors of 123456762:
Prime factors of 123456763:
Prime factors of 123456764:
Prime factors of 123456765:
Prime factors of 123456766:
Prime factors of 123456767:
Prime factors of 123456768:
Prime factors of 123456769:
Prime factors of 123456770:
Prime factors of 123456771:
Prime factors of 123456772:
Prime factors of 123456773:
Prime factors of 123456774:
Prime factors of 123456775:
Prime factors of 123456776:
Prime factors of 123456777:
Prime factors of 123456778:
Prime factors of 123456779:
Prime factors of 123456780:
Prime factors of 123456781:
Prime factors of 123456782:
Prime factors of 123456783:
Prime factors of 123456784:
Prime factors of 123456785:
Prime factors of 123456786:
Prime factors of 123456787:
Prime factors of 123456788:
Prime factors of 123456789:
3 3 3607 3803
This is copied and pasted from the sample output, so the numbers are wrong, but it basically prints just the last number's prime factors, instead of all 30. Also, it prints it on the next line, because i used println, but if I use print then it all goes into a big mess.
The output is supposed to look like this:
Prime factors of 123456760: 2 2 2 5 7 271 1627
Prime factors of 123456761: 123456761
Prime factors of 123456762: 2 3 3 11 13 47963
Prime factors of 123456763: 4021 30703
Prime factors of 123456764: 2 2 617 50023
Prime factors of 123456765: 3 5 523 15737
Prime factors of 123456766: 2 1051 58733
Prime factors of 123456767: 7 17636681
Prime factors of 123456768: 2 2 2 2 2 2 2 2 3 160751
Prime factors of 123456769: 53 283 8231
Prime factors of 123456770: 2 5 29 425713
Prime factors of 123456771: 3 3 3 17 268969
Prime factors of 123456772: 2 2 30864193
Prime factors of 123456773: 11 83 135221
Prime factors of 123456774: 2 3 7 7 419921
Prime factors of 123456775: 5 5 13 19 19993
Prime factors of 123456776: 2 2 2 79 195343
Prime factors of 123456777: 3 5779 7121
Prime factors of 123456778: 2 23 1531 1753
Prime factors of 123456779: 109 173 6547
Prime factors of 123456780: 2 2 3 3 5 47 14593
Prime factors of 123456781: 7 41 149 2887
Prime factors of 123456782: 2 61728391
Prime factors of 123456783: 3 2797 14713
Prime factors of 123456784: 2 2 2 2 11 11 43 1483
Prime factors of 123456785: 5 24691357
Prime factors of 123456786: 2 3 20576131
Prime factors of 123456787: 31 31 128467
Prime factors of 123456788: 2 2 7 13 17 71 281
Prime factors of 123456789: 3 3 3607 3803
So how do I make all 30 prime factorizations happen? I've been staring at this code for some time now and I can't figure it out.
So how do I make all 30 prime factorizations happen? I've been staring at this code for some time now and I can't figure it out.
Now, that is a nice problem..
So, you are given a number N and you want to produce all tuples (p_1, \ldots, p_k) such that forall i the number p_i is prime and p_1 \ldots p_k = N. Well, take all prime numbers p_1 such that N' = N / p_1 is an integer and complete the tuple with all solutions for N'. The case when N is prime is trivial.
You need one extra twist to ensure uniqueness.
factoring(min_prime, number)
if number = 1 return {()} /* one empty factoring */
sol = {} /* empty set */
for i = min_prime to number, where i is prime and a divisor of number
append to sol the result of prepending i to each factoring(i, number / i)
return sol
The Idiot
Nov15-04, 01:30 PM
Here's what I would do.
Look at this line of code:
for (number=432731; number > 432701; number--)
System.out.println("Prime factors of " + number + ":");
Try something like this:
for (number=432731; number > 432701; number--)
{
System.out.print("Prime factors of " + number + ":");
factor(number);
}
"factor" would print out the factors, and at the end, before returning, would print a '\n'. The reason that you're not printing out all the factors of all the numbers is that it's simply not included in that "for" loop.
Getting back to Java:
I don't really understand the "object-orientedness" of Java's code related to exceptions.
For example, if I have a try {
//blah, blah. blah
System.out.println(s1);
//blah, blah. blah
}
catch([some kind of exception] e1) {
// "e1" handling code
}
catch(NullPointerException e2) {
// "e2" handling code
}
.
.
.
catch(Exception e6){
// "catch-all" handling code
}
// and so on...
that list of "catches" looks roughly -- very roughly-- like a C switch statement, but different...
So what is the difference? What exactly is the statement
catch(NullPointerException e2) doing that's different from a switch? Is NullPointerException e2 a constructor of some object?
In this example, e2 seems to be an identifier; is it a reference to a "NullPointerException" object? In the examples I've seen, it looks like each "catch" statement has a unique identifier. But what purpose does it serve? I haven't seen any code that makes use of it.
What do you use for a null char in java?
I'm using '\0' and it seems to work. Was I just lucky?
gnome,
The exception handling mechanism in Java is almost (!) the same as a switch statement in C.
The principal ideas are:
1) all exceptions are subclasses of a single class, java.lang.Exception.
2) each catch statement acts more or less like a method declaration.
3) the first catch clause encountered with a matching type is run.
Let's imagine that we have a piece of code that looks through a phone book; if you give it a phone number, it will figure out the name of the person who owns it. This piece of code might throw two kinds of exceptions: a NumberFormatException, if the provided phone number is not a valid phone number, or a NoSuchPersonException, if the phone number was valid but not in the phone book. Let's say the method was defined somewhere in this fashion:
String reverseLookup(String phoneNumber) throws NumberFormatException, NoSuchPersonException
{
...
}
If you made use of this piece of code in a GUI program, you would probably want to tell your user about each kind of error differently. If the user typed the phone number incorrectly, you might want to remind the user how phone numbers should be entered. If the phone book entry was not found, you'd want to tell the user the phone number was valid, but not assigned.
On the other hand, if you were writing some kind of a database utility that does automated processing of phone book data, you wouldn't necessarily want to deal with the two kinds of errors differently. You might just want to make a note in the log indicating a failure and move on.
Here's the code that you might use in the GUI app:
try
{
String name = reverseLookup(phoneNumber)
}
catch (NumberFormatException e1)
{
System.out.println("Make sure phone numbers are entered as (xxx) xxx-xxxx.");
}
catch (NoSuchPersonException e2)
{
System.out.println("Sorry, the owner of that phone number was not found.");
}
And here's the code you might use in the database application:
try
{
String name = reverseLookup(phoneNumber)
}
catch (Exception e)
{
System.out.println("An error occured on phone number " + phoneNumber + ": " + e);
}
The GUI example has separate catch clauses for both kinds of possible exceptions, since it handles them differently. When an exception is thrown, the first matching catch clause is run.
In the database example, there is only one catch clause, and it catches any kind of exception. (Remember, both NumberFormatException and NoSuchPersonException are both subclasses of Exception, so this single catch clause will catch either.)
The catch clause receives (in much the same way as a method) an argument, the exception object itself that was thrown. If the reverseLookup() method needs to throw an exception, it first creates the exception object, then throws it, as such:
if (...)
{
throw new NumberFormatException("This is not a valid phone number.");
}
That NumberFormatException is created with one argument, a human-readable message. It is then thrown, and automatically passed to the first catch clause that matches its type. That catch clause can examine the exception to see what action needs to be taken. In the case of the GUI example I provided above, neither exception is actually examined; the program prints a different error message solely based on the type of exception thrown. In the database example I provided above, the message of the exception, which is presumably meaningful to the operator, is simply printed to standard output. As you can guess, it's a good practice to provide some kind of human-readable message anytime you throw an exception.
- Warren
The null char (the character with ASCII code 0, NUL) in Java is indeed '\0', just like it is in C. Of course, Java Strings don't have much in common with null-terminated C-style strings, so '\0' find much less purpose in Java.
- Warren
Thanks very much, Warren. Now I see why that identifier is useful.
After reading your explanation, I tried some experiments and it all makes much more sense now. The 'e' in "catch(EmptyQueueException e)" is indeed an identifier (I know that because when I tried omitting it I got a compile error -- "<identifier> expected". And specifically, it is a reference to an EmptyQueueException (a class I defined, which of course extends the Exception class).
And when (following your example) you write System.out.println("blah blah blah" + e);you are invoking e.toString().
Which means that the built-in Exception class must implement its toString() method as the equivalent ofString toString() {return this.getClass().getName();}Correct?
And when my Queue class throws an EmptyClassException, the combination of that "throw" and the catch(EmptyQueueException e) is equivalent to a command EmptyQueueException e = new EmptyQueueException();Correct?
------------------------------------------------------------------------
As to the '/0', I was playing around with a getLine() method, using a char variable "in"in = (char)System.in.read();and wanted to be sure "in" was initiated to null (in case there turned out to be nothing to read).
Anyway, thanks again for your help. I hate to just mimic code without understanding what it's actually doing.
The 'e' in "catch(EmptyQueueException e)" is indeed an identifier (I know that because when I tried omitting it I got a compile error -- "<identifier> expected". And specifically, it is a reference to an EmptyQueueException (a class I defined, which of course extends the Exception class).
Yep, 'e' is just a name for thrown argument -- it becomes a variable local to the catch clause itself. You can name it anything you'd like -- unfortunately, two catch clauses cannot use the same name.
Which means that the built-in Exception class must implement its toString() method as the equivalent of... Correct?
Yes, except you might want to provide more information in the String you produce beyond just the name of the class. The Exception class includes a "message" field that contains a (human-readable) descriptive String so that you can customize the Exception.
For example, if a piece of code can throw the same kind of exception from multiple places, it's a good idea for each for each thrown exception to contain a descriptive string specific about each place.
And when my Queue class throws an EmptyClassException, the combination of that "throw" and the catch(EmptyQueueException e) is equivalent to a command... Correct?
Yes, you can think of the throw-catch system as a fancy "break" statement. When an exception is thrown, the try block or method containing the throw is immediately exited, and the nearest agreeable catch block is sought. When it is found, it is immediately run. If none is found, the exception will propagate all the way out to the interpreter itself, which will generally shut down your program.
- Warren
Some additional information: Exceptions aren't the only things that can be thrown -- anything implementing the interface Throwable is fair game. There are two branches by default. One has the parent class Exception, and the other Error. In general, though, you won't bother with Errors.
(It is Error, right? It's been so long I forget... I've always just manipulated Throwables when I got that high level)
Yes, Hurkyl, you got it right. The difference is that Errors are generally not intended to be catchable. When an Error is thrown, the program should terminate immediately.
- Warren
It sounds like you are talking about two different descriptive strings:
For example, if a piece of code can throw the same kind of exception from multiple places, it's a good idea for each for each thrown exception to contain a descriptive string specific about each place.
Here I think I place that descriptive string as an argument to the "throw", as in
throw new EmptyQueueException("The queue is empty, stupid");...(except, well, maybe a more informative string would be better) so the same exception gives a different message specific to the section of code that threw the exception.
------------------------------------------------------------
The Exception class includes a "message" field that contains a (human-readable) descriptive String so that you can customize the Exception.
Here, are you saying that if I define my own exception class I can give it an attribute:
(private?? public??) message "The queue is empty, stupid";
And then what? Would System.out.print(e); then print that message instead of or in addition to the name of the Exception?
It sounds like you are talking about two different descriptive strings:
Nope, just one.
Let's look at some relevant bits of the Exception class's source:
/*
* @(#)Exception.java 1.30 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang;
/**
* The class <code>Exception</code> and its subclasses are a form of
* <code>Throwable</code> that indicates conditions that a reasonable
* application might want to catch.
*
* @author Frank Yellin
* @version 1.30, 01/23/03
* @see java.lang.Error
* @since JDK1.0
*/
public class Exception extends Throwable {
static final long serialVersionUID = -3387516993124229948L;
...
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public Exception(String message) {
super(message);
}
...
}
There's a constructor for the Exception class which accepts a message -- something intended to be human-readable, to describe what happened.
The Exception class is a subclass of Throwable. Let's look at the abbreviated Throwable source:
/*
* @(#)Throwable.java 1.51 03/01/23
*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang;
import java.io.*;
public class Throwable implements Serializable {
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -3042686055658047285L;
...
/**
* Specific details about the Throwable. For example, for
* <tt>FileNotFoundException</tt>, this contains the name of
* the file that could not be found.
*
* @serial
*/
private String detailMessage;
...
/**
* Constructs a new throwable with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* <p>The {@link #fillInStackTrace()} method is called to initialize
* the stack trace data in the newly created throwable.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public Throwable(String message) {
fillInStackTrace();
detailMessage = message;
}
...
/**
* Returns the detail message string of this throwable.
*
* @return the detail message string of this <tt>Throwable</tt> instance
* (which may be <tt>null</tt>).
*/
public String getMessage() {
return detailMessage;
}
/**
* Creates a localized description of this throwable.
* Subclasses may override this method in order to produce a
* locale-specific message. For subclasses that do not override this
* method, the default implementation returns the same result as
* <code>getMessage()</code>.
*
* @return The localized description of this throwable.
* @since JDK1.1
*/
public String getLocalizedMessage() {
return getMessage();
}
...
/**
* Returns a short description of this throwable.
* If this <code>Throwable</code> object was created with a non-null detail
* message string, then the result is the concatenation of three strings:
* <ul>
* <li>The name of the actual class of this object
* <li>": " (a colon and a space)
* <li>The result of the {@link #getMessage} method for this object
* </ul>
* If this <code>Throwable</code> object was created with a <tt>null</tt>
* detail message string, then the name of the actual class of this object
* is returned.
*
* @return a string representation of this throwable.
*/
public String toString() {
String s = getClass().getName();
String message = getLocalizedMessage();
return (message != null) ? (s + ": " + message) : s;
}
...
}
As you can see, it contains a field, called detailMessage, to store the human-readable explanation. When you create an Exception with such a message, it is passsed to the Throwable constructor, which stores it. When the Throwable's toString() method is called, it will include that message in its output, if one is available.
Here I think I place that descriptive string as an argument to the "throw", as in
It's not an argument to throw, it's an argument to the Exception's constructor. Remember, it says "throw new EmptyQueueException". You're creating a new EmptyQueueException object, with the specified message string, then throwing it.
Here, are you saying that if I define my own exception class I can give it an attribute:
(private?? public??) message "The queue is empty, stupid";
And then what? Would System.out.print(e); then print that message instead of or in addition to the name of the Exception?
You got it -- as the source of the Throwable class shows.
- Warren
Got it. Thanks again.
It's a heckuva lot clearer after seeing those source-code snippets. The API on Sun's website shows how (very briefly), but not why.
EUROPE1
Mar17-05, 07:09 AM
I would like to encrypt an object to a cypher in Java and then retrieve it some later time. However the encryption methods in Java take byte arrays as arguments. Is there any way in Java to convert an object to a byte array and later convert the byte array to an object? I know that serialization is done with streams, but I don't know with byte arrays.
Thanks!
so-crates
Mar17-05, 12:08 PM
I would like to encrypt an object to a cypher in Java and then retrieve it some later time. However the encryption methods in Java take byte arrays as arguments. Is there any way in Java to convert an object to a byte array and later convert the byte array to an object? I know that serialization is done with streams, but I don't know with byte arrays.
Thanks!
The only way I would imagine to do it would be to define a custom method called toByteArray() and fromByteArray() (or a constructor) which converts your object to and from arrays of bytes.
ramollari
Mar17-05, 01:22 PM
I think you can use classes ByteArrayInputStream and ByteArrayOutputStream, which write bytes to or from byte arrays with streams. Then you can utilize the writeObject() and readObject() methods of the stream classes.
There are two classes, ByteArrayInputStream and ByteArrayOutputStream, that place stream interfaces around a byte[] array.
You can use standard Java serialization, writing to such a ByteArrayOutputStream.
- Warren
Hello, everyoone, i am a linguist teacher studying math as my second degree,
i don't know computer much, i have a little problem writing a java program to draw graph simultanously to reading raw datafrom a file. graph illustrate data read in.
Can u help give me the code or show me how to code it ??? I read only a few pages of java2 self study guides.
I hope what you helps me might help someone who searchs a lot these days but unable to find anything.
Thank you very much.
Can u help give me the code or show me how to code it ??? I read only a few pages of java2 self study guides.
Read some more. I doubt very much that you'll get people writing code for you.
Sorry, although i read , i still can't have time to to finish it because I busy with teaching, my girlfriend needs it, i see she searched internet a lot. i just nneed hints you can tell so i can tell her then.
I need you just give a bit of help for me, please.
Nomy-the wanderer
Jul16-05, 03:52 AM
I'm learning Java bymyself using The complete reference of java 2, fifth edition, Herbert Schildt..
I don't use sun's SDK, instead i'm using eclipse..
I was trying to make a small array thingy and here's the code
public class twod {
public static void main(String args[]) {
int twod [][] = new int [4][5];
int i, j, k = 0;
for (i=0; i < 4; i++)
for (j=0; j < 5; j++) {
twod[i][j]= k;
k++;
}
for (i=0; i < 4; i++){
for (j=0; j < 5; j++);
System.out.print( twod [i][j] + " "); System.out.println();
}
}
}
And here's the error...
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException:5
at arrays.twod.main(twod.java:29)
Which is in bold above...It seems to me that the code is correct, i still don't understand what's wrong with the print code..
Nomy,
The line "for (j=0; j < 5; j++);", just above your System.out.println() call, is wrong. You should not have a semicolon there; instead, you should have an open brace. The semicolon indicates that the for loop is an empty loop, with nothing inside it.
The problem is that a for loop that increments j from 0 to less-than-5 will actually leave the value 5 in the j variable when it's done. The foor loops runs until the condition fails, and the variable j has to contain the value 5 for the condition to fail.
The System.out.println() call is being made -after- the for loop, since the loop is empty. At that point, j contains 5, and you're accessing the array outside its bounds.
- Warren
Nomy-the wanderer
Jul20-05, 04:33 PM
Thanks a lot Chroot, now i understand...
Your algorithm looks like what you did try to implement than it inadvertently turns out to be like that...:biggrin:
Chroot :wink:, I guess nomy wanted to print out the matrix with a semi-colon unfortunately appeared after the second for-loop as an apparent failure for the program to compile, and an exception is thrown right then to indicate the mistake.
hi, do u have any idea how i can cover the entire screen including the taskbar with an image as soon as a client starts, till a password is provided by the server??? The client should not be able to see anything, not even the taskbar till the administrator provides the right password. This has to be done in java... and soon... can u help???
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.