Java question

VuLakAerr

Member
Jul 8, 2004
34
0
0
Grade 11 course, we use Java: Ready to Program.

This simple program is supposed to generate random numbers simulating the rolling of dice everytime it is loaded. This is just an example program to learn the basics of generated data.

I know this is probably a very simple problem, but I am completely new to Java, and our teacher simply does not teach.



This is what I have so far


// The "Chapter6" class.
import java.awt.*;
import hsa.Console;
import java.io.PrintWriter;
import java.io.FileWriter;

public class Chapter6
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

int die1, die2, roll;
PrintWriter output;
output = new PrintWriter (new FileWriter ("dice"));
for (int count = 1; count <=300;count ++)
{



die1 = (int) (Math.random()*6)+1;
die2 = (int) (Math.random()*6)+1;

roll = die1 + die2;
output.println (roll);

{

output.close();

}
}


When it's run, I get this part highlighted

output = new PrintWriter (new FileWriter ("dice"));

and the error message is:
The constructor "FileWriter" can throw the checked exception "java.io.IOException", so the class creation must be enclosed in a try statement that catches the exception, or else the method must be declared to throw the exception.

Any help would be greatly appreciated.
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
You've used try/catch blocks with exceptions?

ChurchillObjects tutorial on them.

You pretty much have to enclose everything that could throw an error in a try, then you put your cath block giving the exception type you want tp be able to catch after it.


try{

FileInputStream fis = new FileInputStream("data.txt");

//work with the file in here

}
catch(IOException e)
{

//handle anything with the exception here

}

Edit: Why are you importing java.awt when you aren't using anything from it?
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
You need to do exactly what its telling you.

This statement: "output = new PrintWriter (new FileWriter ("dice"));"
may throw an exception. Exceptions occur for a variety of reasons (especially the IOException this refers to). When a function is labeled as "throw IOException" or "throw XXXXXException" it means that any code calling that function must be prepared to handle the exception that may occur.

What you need to do is:

try {
output = new PrintWriter (new FileWriter ("dice"));
} catch (IOException ioe) {
System.out.println("an IO error occurred while attempting to create a FileWriter to file "dice");
}

You can also do various things with the exception object, such as print its embedded message:

System.out.println(ioe);

or print the call stack that created the exception:

ioe.printStackTrace();

 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Exceptions are java's way of expressing that something has gone wrong. They are a special kind of class that you can "throw" which means that they will interrupt all running code back up the call stack until you "catch" them. So when you try to open the file, if there is an error opening the file an exception will be thrown.

The proper solution is to catch the exception, print an error message and exit but if you haven't learned about exceptions yet you may want to hold off on that. The quickest way is to change the declaration of main to:

public static void main(String[] args) throws IOException
{ ... }

Then, if the exception is thrown your program will end and the exception details will be printed out. Note that you will also have to import java.io.IOExcpetion. If you'd like to know how to catch the exception properly let us know and we'll teach you :)

Edit: :confused: beaten to the punch twice :confused: Oh well, I guess you've already been taught how to catch exceptions :p
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Exceptions indicate that some kind of error has occurred. In Java, you must declare (in the function declaration, sayings "throws Exception") or catch exceptions. So, what the compiler is telling you is that there are calls in your code that can raise exceptions, so you need to do something about it. A quick solution would be to wrap each of the troublesome function calls in a try/catch block:

try {
output = new PrintWriter( new FileWriter( "dice" ) );
} catch ( java.io.IOException e ) {
//Do stuff to fix mistake or notify caller of problem
}

You'll probably do best to wrap every throwable function call in try/catch blocks.

Edit: Whoa. Quick repsonses =)
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
Wow, thanks for the quick responses. You guys really know what you're talking about, but it's as if you are speaking a different language to me. I'm having a hard time learning java, and with what you guys said, this is what I came out with..yeah, I'm laughing at it too.

// The "Chapter6Number1" class.
import java.awt.*;
import hsa.Console;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.IOException;

public class Chapter6Number1
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

int die1, die2, roll;
PrintWriter output;
try{

FileInputStream fis = new FileInputStream("dice.txt");

//work with the file in here

for (int count = 1; count <=300;count ++)

die1 = (int) (Math.random()*6)+1;
die2 = (int) (Math.random()*6)+1;

}
{
roll = die1 + die2;
output.println (roll);



output.close();
c.println ("Simulated data of 300 throws now in file 'dice'");



catch(IOException e)





}



} // main method
} // Chapter6Number1 class

I keep getting "Insert "Finally" to complete TryStatement

I've tried putting that expression in a few times and still a no-go Sorry for this, but I honestly have no idea what I am doing ( despite the fact that it was explained well by you guys)
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
Originally posted by: VuLakAerr
Wow, thanks for the quick responses. You guys really know what you're talking about, but it's as if you are speaking a different language to me. I'm having a hard time learning java, and with what you guys said, this is what I came out with..yeah, I'm laughing at it too.

// The "Chapter6Number1" class.
import java.awt.*;
import hsa.Console;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.IOException;

public class Chapter6Number1
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

int die1, die2, roll;
PrintWriter output;
try{

FileInputStream fis = new FileInputStream("dice.txt");

//work with the file in here

for (int count = 1; count <=300;count ++)

die1 = (int) (Math.random()*6)+1;
die2 = (int) (Math.random()*6)+1;

}
{
roll = die1 + die2;
output.println (roll);



output.close();
c.println ("Simulated data of 300 throws now in file 'dice'");



catch(IOException e)





}



} // main method
} // Chapter6Number1 class

I keep getting "Insert "Finally" to complete TryStatement

I've tried putting that expression in a few times and still a no-go Sorry for this, but I honestly have no idea what I am doing ( despite the fact that it was explained well by you guys)

You aren't aliging your brackets.
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
The alignment of the brackets doesn't actually affect the program does it? Just makes it easier to read. Right?
 

pkananen

Senior member
Mar 13, 2003
644
0
0
Originally posted by: VuLakAerr
The alignment of the brackets doesn't actually affect the program does it? Just makes it easier to read. Right?

the program can ONLY function if the brackets ARE aligned.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Originally posted by: VuLakAerr
The alignment of the brackets doesn't actually affect the program does it? Just makes it easier to read. Right?

Indentation, you're correct (except Python =P). Brackets and parentheses must be aligned, however - for each open, there must be a close.

BTW, where is "output" initialized?

Something looking like the attached code?


Edit: You'd also need to declare fis outside of my main try block, if you want it visible in the finally block (I think).
 

clamum

Lifer
Feb 13, 2003
26,252
403
126
Are you supposed to have just the line that could thrown an exception (the FileInputStream one) or does it not matter if you include a bunch of other lines of code in the try { } block? Just wondering...
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
I still can't get it to execute properly. I honestly hate this program.

Thanks for the help, though.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Originally posted by: VuLakAerr
I still can't get it to execute properly. I honestly hate this program.

Thanks for the help, though.

What's the error? I'm bored, so humor me :p
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
Originally posted by: clamum
Are you supposed to have just the line that could thrown an exception (the FileInputStream one) or does it not matter if you include a bunch of other lines of code in the try { } block? Just wondering...

It completely depends on the context. If the rest of the code depends on a statement that could throw an exception executing properly, then there is a logical reason to include it in the try block (or you can add find another way to exit in the catch block, but this can cause issues of readability).

If there are multiple lines in one section that all throw the same exception, there's another reason to group them inside one block.

On the otherside, if you have gigantic try statements, where exactly is throwing the exception can become unclear. In the worst case, stuffing too much in a try block may hide compiler errors about lines further down throwing an exception. You may have overlooked these and not designed your catch clause to handle these cases, and so your program does not function correctly.

It's really a balance of readability and logical program flow that dictate how much or how little is included in each try block.
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
I sorta just tossed in the code you previewed a few posts up.

// The "Chapter6" class.
import java.awt.*;
import hsa.Console;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.IOException;

public class Chapter6
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();

int die1, die2, roll;
PrintWriter output;

try{

FileInputStream fis = new FileInputStream("dice.txt");

//work with the file in here

for (int count = 1; count <=300;count ++) {
die1 = (int) (Math.random()*6)+1;
die2 = (int) (Math.random()*6)+1;
roll = die1 + die2;
output.println (roll);
}
c.println ("Simulated data of 300 throws now in file 'dice'");

} catch(IOException e) {
// No error message
} finally {
// Make sure the resources you used are closed
try { output.close(); } catch ( IOException e ) {}
try { fis.close(); } catch (IOException e ) {}
}

} // main method
} // Chapter6 class


This gets highlighted:

try { output.close(); } catch ( IOException e ) {}


with the error message:

This catch block is unreachable because there is no exception whose type is assignable to "Java.io.IOException that can be thrown during execution of the body of the try block.

and the other error:

try { fis.close(); } catch (IOException e ) {}

message: No field named "fis" was found in type Chapter6
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Hmm. The first error is caused by the fact that the blocks define scope - something declared within is not visible without. That's why in the affixed code I moved the declaration of fis outside of the blocks. It's now initialized within.

The second error is because PrintWriter.close() doesn't throw an exception. I assumed it would, and I was wrong.

I still don't see where output, your PrintWriter, is being created or beind used (declaring it is not enough, it must be instantiated). Unless you need it for the assignment, you can probably make due with using your Console class for output (that's what it's for, right?). If you want/need to use the printWriter, you'll need to call its constuctor as
PrintWriter output = new PrintWriter( <filename> );
or
PrintWriter output = new PrintWriter( <OutputStream> );
or one of the other variations:http://java.sun.com/j2se/1.5.0...va/io/PrintWriter.html
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
Originally posted by: Kilrsat
Originally posted by: clamum
Are you supposed to have just the line that could thrown an exception (the FileInputStream one) or does it not matter if you include a bunch of other lines of code in the try { } block? Just wondering...

It completely depends on the context. If the rest of the code depends on a statement that could throw an exception executing properly, then there is a logical reason to include it in the try block (or you can add find another way to exit in the catch block, but this can cause issues of readability).

If there are multiple lines in one section that all throw the same exception, there's another reason to group them inside one block.

On the otherside, if you have gigantic try statements, where exactly is throwing the exception can become unclear. In the worst case, stuffing too much in a try block may hide compiler errors about lines further down throwing an exception. You may have overlooked these and not designed your catch clause to handle these cases, and so your program does not function correctly.

It's really a balance of readability and logical program flow that dictate how much or how little is included in each try block.


:thumbsup:
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
Thanks for all the help, this is what I have managed to come out with.


// The "Chapter6" class.
import java.awt.*;
import hsa.Console;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.IOException;

public class Chapter6test {
static Console c; // The output console

public static void main (String[] args) {
c = new Console ();

int die1, die2, roll;
// PrintWriter output;

////////
FileInputStream fis;
////////

try{

fis = new FileInputStream("dice.txt");

//work with the file in here

for (int count = 1; count <=300;count ++) {
die1 = (int) (Math.random()*6)+1;
die2 = (int) (Math.random()*6)+1;
roll = die1 + die2;
// output.println (roll);
c.println( roll );
}

c.println ("Simulated data of 300 throws now in file 'dice'");

} catch(IOException e) {
// No error message
} finally {
// Make sure the resources you used are closed
// try { output.close(); } catch ( IOException e ) {}

}
} // main method
} // Chapter6 class



It now executes, and stores 300 random numbers in "dice.txt", but the results don't actually display on the console when executed, which is what I need to know because the actual assignment for this chapter is to have random numbers generated every time the program is executed. How come the random numbers aren't displaying? Thanks a lot.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
Do the assignment specs tell you to store in the file? Or was that optional? Store and display to the console?

Also, from the looks of it, you'll be wanting to use a FileOutputStream (write out, read in) instead of a FileInputStream. Then, where the line is commented out, use " fos.println( roll );".

For quick console access, you can use System.out.println(). But it looks like they're having you use a special package (hsa) for those purposes (Is that what Console is for?).
 

VuLakAerr

Member
Jul 8, 2004
34
0
0
The assignment is to have the numbers displayed and saved to a file, yes.

As for the hsa package, I'm not sure if we need to have it. I doubt it, though.

Edit: Awesome man, your suggestion to use Outputstream instead of Input worked perfectly.

Thank you, and everyone else who helped me.

Great to know theres a place where people assist newcomers.

Thanks again, everyone.