Java Welcome to Java Class: Learn Java One Bit at a Time

AI Thread Summary
The discussion focuses on learning Java programming step by step, emphasizing the need for a compiler and a runtime environment. The Java compiler converts source code into bytecode, which is executed by a Java Virtual Machine (JVM), allowing Java programs to run on any platform. Participants are guided through the installation of the Java J2SE 1.4.2 SDK and the process of compiling and running a simple Java program. Clarifications are provided on terminology, such as the difference between source code and object code, and the function of convenience files for compiling and running programs. The conversation also addresses troubleshooting issues related to running Java applets and classpath configurations.
  • #101
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.
 
Technology news on Phys.org
  • #102
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);


}
}
}
}
 
  • #103
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.
 
  • #104
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.
 
Last edited:
  • #105
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.
 
  • #106
prime factorizations

ek said:
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&#039; = N / p_1 is an integer and complete the tuple with all solutions for N&#039;. The case when N is prime is trivial.

You need one extra twist to ensure uniqueness.

Code:
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
 
  • #107
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.
 
  • #108
exception handling

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
Code:
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.
 
  • #109
java: null character

What do you use for a null char in java?

I'm using '\0' and it seems to work. Was I just lucky?
 
  • #110
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:

PHP:
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:

PHP:
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:

PHP:
try
{
	String name = reverseLookup(phoneNumber)
}
catch (Exception e)
{
	System.out.println("An error occurred 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:

PHP:
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
 
  • #111
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
 
  • #112
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
Code:
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 of
Code:
String 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
Code:
EmptyQueueException e = new EmptyQueueException();
Correct?

------------------------------------------------------------------------

As to the '/0', I was playing around with a getLine() method, using a char variable "in"
Code:
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.
 
  • #113
gnome said:
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
 
  • #114
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)
 
  • #115
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
 
  • #116
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
Code:
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?
 
  • #117
gnome said:
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:

PHP:
/*
 * @(#)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:

PHP:
/*
 * @(#)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
 
  • #118
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.
 
Last edited:
  • #119
Help!

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!
 
  • #120
EUROPE1 said:
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.
 
  • #121
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.
 
  • #122
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
 
  • #123
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.
 
  • #124
boteet said:
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.
 
  • #125
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.
 
  • #126
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[j]= k;
k++;

}
for (i=0; i < 4; i++){
for (j=0; j < 5; j++);

System.out.print( twod [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..
 
  • #127
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
 
  • #128
Thanks a lot Chroot, now i understand...
 
  • #129
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.
 
  • #130
help!

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?
 

Similar threads

Replies
3
Views
1K
Replies
33
Views
8K
Replies
7
Views
3K
Replies
5
Views
2K
Replies
13
Views
3K
Back
Top