JamesKox 0 Light Poster

Huh? The main method is the method that runs automatically when you run a .java file, or when you click 'run' (or the corresponding button) in Eclipse or Netbeans or whatever editor you use. If this isn't the case, then tell me what method is running first in your code...

I'm using BlueJ, there's no run button or anything like that.

I have to create a new object. The is done with the "Reporter()" method and it opens up a terminal window, that outputs this...

WeatherStation in TROPICAL zone created
WeatherReport for Mt Erebus created

In the first post, that's the whole class and the methods that are in it.

If you can't work out my program, then it's alright, i keep looking at it until i solve the problem.

JamesKox 0 Light Poster

I don't know how to do that.

When i create a method i don't set it up like that.

JamesKox 0 Light Poster

post your main method...

Well they are all relavent, but this is probably the important one...

public Reporter(String where)
    {
        ws = new WeatherStation(where);
        wr = new WeatherReport();
    }
JamesKox 0 Light Poster

Here's a question i got in my assignment...

Create a method with signature

public String testWindDirection()

that creates a local object of type WeatherReport using the constructor with no parameters,
and returns its initial wind direction, e.g "ESE"

I createrd it here...

public class Reporter
{
    private WeatherStation ws;
    private WeatherReport wr;
    private WeatherStation temperature;
    private WeatherReport winddir;
 
    /** Constructor for objects of class Report
     */
    public Reporter()
    {
        ws = new WeatherStation("Tropical");
        wr = new WeatherReport();
    }
    
    /** Returns initial temperature value
     */
    public int testTemperature()
    {
        temperature = ws;
        return temperature.getTemperature();
    }
    
    /** Comment...
     */
    public String testWindDirection()
    {
        this.winddir = wr;
        return winddir.getWindDirection();
    }
    
     /**
     * Constructor for objects of class Report
     * @param where Location?
     */
    public Reporter(String where)
    {
        ws = new WeatherStation(where);
        wr = new WeatherReport();
    }
}

This runs, but doesn't produce the exact result. Here is the error i get when it is tested...

The output should have been:
WeatherStation in TROPICAL zone created
WeatherReport for Mt Erebus created
Test 2
WeatherReport for Mt Erebus created
Default WeatherReport has wind direction of S

This is what was actually produced:
WeatherStation in TROPICAL zone created
WeatherReport for Mt Erebus created
Test 2
Default WeatherReport has wind direction of S

Can someone see something wrong in my code?

It doesn't produce another WeatherReport for Mt Erebus.

JamesKox 0 Light Poster

Alright, thanks.

JamesKox 0 Light Poster

Sorry, but how do you do that?

JamesKox 0 Light Poster

I edited my post, re-read it. There is no way your file is just named "name". It would be named "name.txt" at the very least. And if it was not in the same directory as your .java file, you would need to specify the directory such as "C:/name.txt" or wherever it is.

Yeah, it works now.

Thanks for the help BestJewSinceJC. :)

JamesKox 0 Light Poster

I get an error that says...

An unhandled exception (class java.io.FileNotFoundException) occurred.
Try again!
JamesKox 0 Light Poster

Hmm. It's possible the code I gave you doesn't work. It's also possible that you aren't creating the FileReader Object correctly, due to having an incorrect pathname for the file. Hold on, let me do a quick test.

Hey BestJewSinceJC

I took out the "" in the FileReader("name") It works, but still not getting the exact result.

I look into some more.

JamesKox 0 Light Poster

Well it runs...

public int fileSize (String name) throws IOException
   {
       int charLength = 0;
       FileReader file = new FileReader("name");
       while (file.read() != -1) {
           charLength++;
        }
        return charLength; 
    }

But doesn't produce the result i want?

Know what's wrong with that?

JamesKox 0 Light Poster

Okay i edited the program...

{
       int charLength = 0;
       FileReader file = new FileReader("name");
       [b]while (file.length()) {[/b]
           charLength++;
        }
        return charLength; 
    }

I get an error that says "cannot find symbol - method length()".

Am i going the right way?

JamesKox 0 Light Poster

Thanks again BestJewSinceJC.

I'm sorting the method out now.

JamesKox 0 Light Poster

No, it does not, because Scanner's hasNext() method does not get the next character, or get anything for that matter. It tells you if the Scanner has any more tokens in its input, and it does not advance past any input. So you'd be sitting in an infinite loop (if there were actually tokens). A token is just matched by the delimiter pattern, which by default, is whitespace. So if you had the following:

blah deee weeee

The first token is blah, the second is deee, and the third is weeee. Anyway, I don't see why you don't just construct the file Object then use the File's length method to see how many bytes are in the File, which tells you how many characters are in the file. Here is the documentation I am referring to when I'm talking about Scanner and File. Although it is a good idea to get familiar with both, so you don't need to look it up.
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNext()

Alternatively, you can either look up FileReader here on Daniweb (this will bring you to other threads where people had similar questions to the one you are asking), or you can look at this documentation: http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html . In particular, consider using the read() method of the FileReader class after you construct your FileReader object. It reads a single character at a time.

The modification of your program, one way or another, to produce the correct result is only one or …

JamesKox 0 Light Poster

I'm was wondering if someone can check if this method produce the right result?

public int fileSize (String name) throws IOException
   {
       int charLength = 0;
       File file = new File("name");
       Scanner input = new Scanner(file);
       while (input.hasNext()) {
           charLength++;
        }
        return charLength; 
    }

What this is supposed to do is count the number of characters in the file whose name is supplied as the name parameter. The method return the number of characters in the file or -1 if an IOException occurs.

I'm not on my computer so i can't test it with the application.

JamesKox 0 Light Poster

1) I said move, not remove.
2) Yes, unless you want 'number' to be set to the number of bytes read on each invocation of that statement in your loop - which negates the whole point of incrementing it inside the loop as a counter.

Okay, thanks.

I've sorted it out and it's now working and giving me the result i want.

Thanks to all the people who helped me with this...

masijade, Ezzaral, JamesCherrill, BestJewSinceJC, abbie and alias120.

I appreciate it.

JamesKox 0 Light Poster

The value of 'number' is what you are wanting to return, since that is your counter variable. Of course, you will have to declare it above the try-catch block to do so... and not reset it every read iteration with this part number = stream.read()

Alright, i want to ask some questions....

1) When i remove the int number = 0; from the try-catch block, what will then go into that?

2) Do i know have to remove number = stream.read() now?

Sorry if these questions are dumb, i just want to make sure that i'm going in the right direction.

Will it be something like this...

public int countNo(InputStream stream)throws IOException
   {
       int number = 0;
       try {
           

            while ((stream.read()) != -1) {
                number++;
            }

        } finally {
            if (stream != null) {
                
            }
        }
        return stream.read();
   }
JamesKox 0 Light Poster

One test program is worth a thousand expert opinions.

(Not that I'm an expert, because frankly, I'm not. But it's the truth.)

Well i removed it and i get a similar error saying...

Your result was -1
It should have been 1854
Try again!

Could it be the "if (stream != null)"?

I'm not quite sure what to do here.

JamesKox 0 Light Poster

start quote:

if (stream != null) {
                stream.close();
}

return stream.read();

Why would you close the stream, then read from it? ....

Okay, so if i remove "stream.close();", will the i get my result as a int instead of a null?

JamesKox 0 Light Poster

Well it compiled and works.

But there's an error (in my course application) that says...

Your result was null
It should have been 1869
Try again!

Do you know what i could do to sort this out?

JamesKox 0 Light Poster

You defined number in the try block. It is out of scope in the finally block. Even if it weren't, it's the stream that you want to check for null - not the number.

Alright. Here's my code now...

public int countNo(InputStream stream)throws IOException
   {
       
       try {
           int number = 0;

            while ((number = stream.read()) != -1) {
                number++;
            }

        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return stream.read();
   }

Let me test it.

JamesKox 0 Light Poster

You read from 'stream'. That is your InputStream object that is being passed into the method.

Okay, silly me.

That's sorted, but when i compile it, it highlights the "if (number != null)" and says "cannot find symbol - variable number".

This is weird, i've initialised number to zero and everything, but why can't it find it?

JamesKox 0 Light Poster

You have those backward. I don't think you intend to read() from 'number'.

What am i supposed to read from?

Sorry, Ezzaral, i don't understand what you mean.

JamesKox 0 Light Poster

Okay masijade,

I went back to the code in the first post and edited like i was instructed the first few replies....

public int countNo(InputStream stream)throws IOException
   {
       
       try {
           int number = 0;

            while ((stream = number.read()) != -1) {
                number++;
            }

        } finally {
            if (number != null) {
                stream.close();
            }
        }
        return number;
   }

When i compile it, it highlights the "while ((stream = number.read()) != -1)" line and says the "int cannot be dereferenced".

Do you know what the problems with this?

JamesKox 0 Light Poster

masijade and other,

To make it clear to you, here's the question i'm trying to answer...

Write a method called countNo which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any >IOExceptions which might occur in the method should be passed back to the method's caller.

Am i going about this the right way?

Also, are you to return the number of bytes, or the number of charatcers? If this is a UTF character stream, those two will be two different things.

It's the number of characters.

JamesKox 0 Light Poster

In your inital post, you were to take an intpustream as the argument and count the number of bytes in it. Now you're talking a byte array? Well, if in that case the purpose is to return the number of bytes in the byte array smply return b.length.

Somehow or another, you seem to keep slipping sideways whenever you "correct" something, rather than coming closer to your goal.

Go back to the very start of this thread, and the code that was posted there, then, go through the first few posts changing only those parts of that code that you were told you needed to change and you will have your solution as of post #6.

Yes i'm taking an InputStream, and trying to read the stream and return the number of characters it contains as an int.

I'll look back at my code.

BTW look at the code above, is that in the right direction?

JamesKox 0 Light Poster

JamesCherrill,

I've edited the code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new ByteArrayInputStream(b);

            while ((b = number.read()) != -1) {
                number++;
            }
        } finally {
            if (number != null) {
                is.close();
            }
        }
        return number;
   }

When i compile it, it highlights the "while ((b = number.read()) != -1)" line, saying the...

int cannot be dereferenced

Do you know what the problem is?

JamesKox 0 Light Poster

1. You got this bit right! ByteArrayInputStream is a subclass of InputStream, ie it's a "kind" of InputStream. You have created an instance of ByteArrayInputStream, and that is a suitable object to set is to.
2. Personally I'd forget the bufferedreader bit, just read directly from is. You can worry about optimising it later.
3. Yes, you got that right as well. In your code you read(), but you assign the result to b, which is a byte array, not an integer as required by the API. Your code also tests for end-of-file by looking for a null value, when it should look for -1.

Thanks for the feed back.

I understand your impatience, but I have a life to live here. People are arriving for dinner in 15 mins (it's 18:45 here) and I have to go now. I'll check this thread again tomorrow

Don't worry, you do your thing.

I'll be working on this code until i get it right.

JamesKox 0 Light Poster

^^^^^^

JamesKox 0 Light Poster

Hi JamesCherrill,

I've edited my code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new ByteArrayInputStream(b);
            BufferedReader br = new BufferedReader(is);

            while ((b = br.read()) != null) {
                number++;
            }
        } finally {
            if (number != null) {
                is.close();
            }
        }
        return number;
   }

Some things here...

1) I've used a ByteArrayInputStream to initialise is as an InputStream, but i don't know how to "instantiate one of its subclasses to get a real input stream to use as its value" - I need help on that.

2) I get an error in the "BufferedReader br = new BufferedReader(is);" line, saying it cannot find symbol contructor BufferedReader. Could that be due the problem i'm having in 1?

3) InputStream.read() returns the next byte of data or -1 if the end of the stream is reached. Is that right? Are you telling me this because there is something wrong in my code? Otherwise i don't understand what you mean.

JamesKox 0 Light Poster

InputStream, as the Java API doc makes very clear, is an abstract class; it's definition is incomplete and you cannot instantiate it with new. It's purpose in life is to define a standard set of operations that any byte-oriented input stream should implement. As also explained in the API doc, it has a number of subclasses that you can instantiate, including one that is based on a byte[] array. So, you can declare is as an InputStream reference variable, but you have to instantiate one of its subclasses to get a real input stream to use as its value.
Finally, it's the input stream you need to close, not your integer.
oh, and ps, read the API doc for InputStream.read() to find out what it returns (hint: it's not a byte array) and what it does when it reaches end-of-file (hint: it doesn't return null).

Thanks, i'm looking into it now.

JamesKox 0 Light Poster

Like the guys above said, you should initialize an integer to zero (in your example, it's "number"). Then start the loop with the first character, go to the last one and keep incrementing unless the string finishes.
So, if you're forced to use InputStream as the parameter, you can use BufferedReader to read the InputStream. For instance, if 'isr' is your InputStream, it's something like BufferedReader br = new BufferedReader(isr);
And converting the inputstream into String (using br.readLine()), you can then count the number of characters in the String. (I really hope you can figure that out now. Actually, we guys have left nothing virtually nothing to figure out).

I'm still having trouble with this...

I've done everything (i think) required, but i'm just not getting the code to compile. Here's my code...

public int read(byte[] b) throws IOException {
       
       try {
            int number = 0;
            InputStream is = new InputStream(b);
            BufferedReader br = new BufferedReader(is);

            while ((b = br.read()) != null) {
                number++;
            }
        } finally {
            if (number != null) {
                number.close();
            }
        }
        return number;
   }

When i compile the code it highlights "InputStream is = new InputStream(b);" and says it can't be instantiated.

Can someone point me to where i'm going wrong with my code? I know that the "InputStream is = new InputStream(b);" line is wrong; i'm trying to use InputStream as a parameter, but i'm doing it all worng. I just need know if i'm in the right direction …

JamesKox 0 Light Poster

Thanks a lot abbie! I appreciate the comment, I'll work something out from it.

JamesKox 0 Light Poster

Still need help with this.

JamesKox 0 Light Poster

Do you know how to declare an int variable?

Do you know how to increment it?

Well, declare one before the while loop, and increment it within the while loop. And, do nothing else inside the while loop.

Hi masijade,

I've just done this and edited the code...

public int read(byte[] b) throws IOException
   {
       int number = 0;
       try {
            number = new FileInputStream("Hello");
            int c;

            while ((c = number.read()) != -1) {
                number++;
            }
        } finally {
            if (number != null) {
                number.close();
            }
        }
        return number;
   }

The code gives me a compile error saying it "found java.io.FileInputStream but expected int". Do you know where i'm going wrong with this? Also am i on the right track with this method so far?

JamesKox 0 Light Poster

Thanks for the replies guys! I'm just coming back to this program today.

BestJewSinceJC, i'm using an inputStream, but your reply has been useful anyways. Thanks.

JamesKox 0 Light Poster

http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html

Check this link out, something information that might prove helpful.

-alias

I've read that, but it doesn't help me with the type of method i'm creating.

That's the first thing i went to when i was creating this method.

I guess i have to do more searching.

JamesKox 0 Light Poster

I thought you wanted to count the bytes, not write them out to something else (and, actually, you're trying to write it out to the inputstream you're currently reading, don't you see something wrong with that?). That should be where you look. Don't you think you should be incrementing a variable there, instead?

Yeah that's what i want to do.

Do you mind if you can give me an example of how to do this (whether a link or a pseudo code)?

That code i wrote was formed through using various examples over the net. I've read about the InputStream, but there seems to be so many different examples on the net/textbook and all of the seem to be complicated.

Or can i get a simple written break down of doing the method please?

JamesKox 0 Light Poster

Hello guys,

I'm trying to create a method where it takes a InputStream as a parameter, reads the stream and returns the number of characters it contains as an int.

I'm having difficulties with this. I've searched the internet for examples, but i can't find one that helps me with the method i'm creating. Here's my code so far...

public int countNo(InputStream stream)throws IOException
   {
       
       try {
            stream = new InputStream();

            while ((stream = input.read()) != -1) {
                input.write(c);
            }

        } finally {
            if (input != null) {
                input.close();
            }
        }
        return stream;
   }

Can anyone here guide me with completing this method, because i'm having difficulties with it.