Results 1 to 20 of 20
Thread: File Out - PrintWriter
- 04-27-2014, 05:54 PM #1
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
File Out - PrintWriter
This program is all about a bicycle class that has two parameters (numberOfWheels,weight) which I would like to have a user input their bike inventory (bikeArray) that will result in a for loop to get all the parameters for the bikeArray. I believe I have accomplished this in the main method (looks messy, not sure if you guys have any tips on how to clean it up). Now the real goal of this assignment is to create a text file (CycleOut.txt) to print all of this data. How do I fix the issue of my variables and array not passing into the next try/catch block? Should I nest Text File (File file) in the previous try block?
Java Code:import java.io.*; import java.util.Scanner; public class CycleMain { //Check constraints are satisfied public static double check(double numberOfWheels, double weight) throws IOException { if (numberOfWheels <= 0 || weight <= 0) { System.out.println("Values must be greater than 0!"); } else { System.out.println("\nNumber of Wheels: " + numberOfWheels); System.out.println("Weight: " + weight); } return 0; } public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); System.out.println("Bike Inventory: "); int inventory = input.nextInt(); Cycle[] bikeArray = new Cycle[inventory]; try { for(int i = 0 ; i < inventory; i++){ System.out.print("Enter number of wheels: "); double numberOfWheels = input.nextDouble(); System.out.print("Enter weight: "); double weight = input.nextDouble(); check(numberOfWheels, weight); bikeArray[i] = new Cycle(numberOfWheels, weight); } } catch (IOException ex) { System.out.println("Exception: Values must be greater than 0."); System.exit(0); } System.out.print("\nExecution continues..."); //Creating text file to store values File file = new File("CycleOut.txt"); try{ PrintWriter output = new PrintWriter(file); output.print(bikeArray[i]); output.print(numberOfWheels); output.print(weight); output.close(); } catch(FileNotFoundException ex){ System.out.println("*** File does not exist! ***"); } } }
- 04-27-2014, 06:26 PM #2
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: File Out - PrintWriter
Declare your variables outside of the try catch block. And doesn't the name bicycle imply two wheels?
Regards,
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 04-27-2014, 06:40 PM #3
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
You will have to ask my professor about that one...lol
In your opinion, is this a legitimate way of completing the assignment? Any food for thought?
**Edit**
Just checked the txt file and its contents are incomprehensible.
Text file:
Cycle@38910040Cycle@37a786c3
Do I need to create a toString method for the bikeArray? If so, where would I do this?Last edited by javaStooge; 04-27-2014 at 06:51 PM.
- 04-27-2014, 07:10 PM #4
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
Something like this:
Java Code:File file = new File("CycleOut.txt"); try{ PrintWriter output = new PrintWriter(file); for(int i = 0 ; i < inventory ; i++) output.print(Integer.toString(bikeArray[i])); //except toString errors //output.print(numberOfWheels); //output.print(weight); output.close(); } catch(FileNotFoundException ex){ System.out.println("*** File does not exist! ***"); } } }
- 04-27-2014, 07:30 PM #5
Senior Member
- Join Date
- Feb 2014
- Posts
- 447
- Rep Power
- 8
Re: File Out - PrintWriter
Hi,
Just a few comments from my side:
If you want some useful text when printing a Cycle, then you should override the toString method of that class.
You check method is checking if the parameters of a cycle are valid or not. So it would belong to the class Cycle and not to CycleMain.
Why does it always return the double value 0? I would expect it to return true or false indicating if it is valid or not.
Why do you ignore the return value when you call check? Checking something and then ignoring the result is not nice.
Maybe you wanted to raise an exception? But invalid user input is nothing exceptional. So a function like isValid should return if something is valid or not but not rising an exception.
I hope these comments was useful for you.
With kind regards,
KonradLast edited by kneitzel; 04-27-2014 at 07:32 PM.
- 04-27-2014, 08:34 PM #6
Senior Member
- Join Date
- Jan 2011
- Location
- Belgrade, Serbia
- Posts
- 311
- Rep Power
- 11
Re: File Out - PrintWriter
Check this
Object (Java Platform SE 7 )
It might better explain toString() to you..
- 04-28-2014, 12:17 AM #7
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
Hey milovan, thanks for the source, but I'm not quite sure I understand it.
So in order to use the toString method for an object array I first need to create get methods for both the class and the actual information I want from that class? Is that why they have:
getClass().getName() +'@' + Integer.toHexString()
What is the purpose of the '@' ? I haven't seen anything like this previously...
- 04-28-2014, 01:54 AM #8
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: File Out - PrintWriter
The @ sign is just the JDK's way of saying you have this object which is located @ memory address. That is the default toString value. So most folks override toString to return a more useful string.
Regards,
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 04-28-2014, 10:01 AM #9
Just a guy
- Join Date
- Jun 2013
- Location
- Netherlands
- Posts
- 5,114
- Rep Power
- 13
- 04-28-2014, 12:08 PM #10
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
Re: File Out - PrintWriter
Ripped from the 1.6 source for the Object class for the hashCode() method:
* As much as is reasonably practical, the hashCode method defined by
* class <tt>Object</tt> does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java<font size="-2"><sup>TM</sup></font> programming language.)
JosBuild a wall around Donald Trump; I'll pay for it.
- 04-28-2014, 12:29 PM #11
Just a guy
- Join Date
- Jun 2013
- Location
- Netherlands
- Posts
- 5,114
- Rep Power
- 13
Re: File Out - PrintWriter
Thank you, that comment proves my statement. Its not a memory address, its a unique number that in the Java 6 Oracle implementation just happens to be a memory address for convenience :) Internal implementation detail, not part of the language specification. And perhaps not part of other runtime implementations either.
"Syntactic sugar causes cancer of the semicolon." -- Alan Perlis
- 04-28-2014, 04:29 PM #12
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: File Out - PrintWriter
The JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 04-28-2014, 04:34 PM #13
Just a guy
- Join Date
- Jun 2013
- Location
- Netherlands
- Posts
- 5,114
- Rep Power
- 13
Re: File Out - PrintWriter
Yep, now its so stretched out that I'm a pedantic ahole in stead of just making a random comment. Yay mission succeeded!
"Syntactic sugar causes cancer of the semicolon." -- Alan Perlis
- 04-28-2014, 05:03 PM #14
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
No idea what the heck you guys were just talking about...and so I'll try to dodge that bullet and move on to my next question regarding the same program...
I've entered my questions in the code below so hopefully that will be able to identify the trouble areas...
Java Code:import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class CycleMain { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); int numberOfWheels, weight; System.out.println("Bike Inventory: "); int inventory = input.nextInt(); Cycle [] bikeArray = new Cycle[inventory]; try { for (int i = 0; i < inventory; i++) { System.out.print("Enter number of wheels: "); numberOfWheels = input.nextInt(); System.out.print("Enter weight: "); weight = input.nextInt(); Cycle.check(numberOfWheels, weight); bikeArray[i] = new Cycle(numberOfWheels, weight); } } catch (IOException ex) { System.out.println("Exception: Values must be greater than 0."); System.exit(0); } System.out.print("\nExecution continues..."); // Creating text file to store values File file = new File("CycleOut.txt"); PrintWriter output = new PrintWriter(file); try { for (int i = 0; i < inventory; i++) output.write(bikeArray.getClass().toString()); //Will this accomplish the task of writing the array output.println(); //to the txt file in correct format? // output.print(numberOfWheels); // output.print(weight); }catch (FileNotFoundException ex) { //How do I get rid of this error? It says that I have not thrown System.out.println("*** File does not exist! ***"); //the exception, which I see,but unsure } //how to fix. finally { output.close(); } Scanner scan = new Scanner(file); //Finally, which I do not fully understand either, will this read the data from the while (scan.hasNext()){ // file and print it in console? I always knew the Scanner to be String stringWheels = scan.next(); //used to read user input...not data from text files and such...?! String stringWeight = scan.next(); System.out.println(stringWheels); System.out.println(stringWeight); scan.close(); } } }
Last edited by javaStooge; 04-28-2014 at 05:07 PM.
- 04-28-2014, 05:23 PM #15
Senior Member
- Join Date
- Feb 2014
- Posts
- 447
- Rep Power
- 8
Re: File Out - PrintWriter
Hi,
first I find it quite hard to search for questions inside the comments of your code. But lets try to answer them:
- bikeArray.GetClass() returns the Class of your array and toString() just gives you the name of the class.
And you had that inside a loop so you write that multiple times.
And also important: You could have started your application to look at that yourself!
If you want to print Wheels and Weight on a line, you could print bikeArray[i].getWheels() and bikeArray[i].getWeight() (if these getters are available). Or you could override the toString() method and do exactly that output in there.
(Just write a method that you call toString() and that prints a line with wheels and weight!)
- A scanner can work on any stream or file. So yes, you can use the Scanner. But you close it inside the while loop which of course stops your reading directly!
- What error do you want to get rid of? Can you give details what you get? I am just wondering what you meant at the catch statement.
Konrad
- 04-28-2014, 06:45 PM #16
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
I would have started my program if it had worked and didn't have errors in it!
The error: This exception is never thrown from the try statement body.
Yes, okay, I saw this, but how is it fixed?
- 04-28-2014, 07:05 PM #17
Senior Member
- Join Date
- Feb 2014
- Posts
- 447
- Rep Power
- 8
Re: File Out - PrintWriter
So just read the error message. What does it tell you? You try to catch an exception that is never thrown. So just remove the catch. And because it is the only catch statement with no other catch or final statement, you can completely remove the try statement, too.
[Edit: I hope this post does not look unfriendly. Your posts asking for help are really welcome! Just try to be more confident with playing around with your code and reading error messages. Often they tell you quite clearly what you could try. It can be quite hard at the beginning but you normally shouldn't damage anything when playing around. I know that it might sound easier than it is.]Last edited by kneitzel; 04-28-2014 at 07:25 PM.
- 04-28-2014, 07:26 PM #18
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Re: File Out - PrintWriter
The problem with that is I need it for the assignment. So do I create a separate method for this code in order to throw the exception?
Last edited by javaStooge; 04-28-2014 at 07:30 PM.
- 04-28-2014, 07:40 PM #19
Senior Member
- Join Date
- Feb 2014
- Posts
- 447
- Rep Power
- 8
Re: File Out - PrintWriter
Ahh ok, now I understand your problem.
That brings me back to your Check method. You already moved it to the Cycle class (thank you). But what is that check doing? There are 2 possibilities:
a) It checks the values and then returns if the data is valid or not (I would prefer a name like isValid over check). if you build it with such a return value, then you have to use it in a way like
Java Code:if (Cycle.isValid(numberOfWheels, weight) { // Do something with the values } else { // return an error message }
The other option is, that your Check method simply throws an exception. That is something that is quite normal for a lot of functions: You check that the arguments are valid.
In such a case, the Check method should not return anything. And you have to extend it:
a) you add a throws IOException to the deklaration of the function (e.g. public static Check(int numberOfWheels, int weight) throws IOException {
b) Inside the function you check the values. If they are not valid, then you throw an exception. e.g. if (weight <0) throw new IOException("Weight must be greater than zero!");
This seems to be the implementation that is requested if I understood you correctly.
*) That part about not using is just my personal opinion. It is something personal and there can be a lot of discussions about the things that I would prefer or not prefer and it is quite likely that others see it different.
Konrad
- 04-29-2014, 07:56 PM #20
Senior Member
- Join Date
- Jan 2014
- Posts
- 106
- Rep Power
- 0
Similar Threads
-
File IO (PrintWriter and Methods)
By rgru25 in forum New To JavaReplies: 8Last Post: 03-14-2013, 03:38 PM -
Need help with PrintWriter!
By PapaEcho in forum New To JavaReplies: 2Last Post: 10-09-2011, 07:51 PM -
printwriter
By sope in forum New To JavaReplies: 2Last Post: 05-09-2011, 08:57 PM -
Help with PrintWriter code
By eel in forum New To JavaReplies: 4Last Post: 09-19-2010, 08:36 AM -
Help with printwriter.
By Addez in forum New To JavaReplies: 2Last Post: 10-30-2009, 02:58 PM
Bookmarks