Results 1 to 20 of 20
Like Tree2Likes
  • 1 Post By jim829
  • 1 Post By kneitzel

Thread: File Out - PrintWriter

  1. #1
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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! ***");
    			}
    	}
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: File Out - PrintWriter

    Declare your variables outside of the try catch block. And doesn't the name bicycle imply two wheels?

    Regards,
    Jim
    javaStooge likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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 05:51 PM.

  4. #4
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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! ***");
    			}
    	}
    }
    error: The method toString(int) in the type Integer is not applicable to the arguments (Cycle)

  5. #5
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    7

    Default 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,

    Konrad
    Last edited by kneitzel; 04-27-2014 at 06:32 PM.
    javaStooge likes this.

  6. #6
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    311
    Rep Power
    10

    Default Re: File Out - PrintWriter

    Check this
    Object (Java Platform SE 7 )

    It might better explain toString() to you..

  7. #7
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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...

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default 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,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: File Out - PrintWriter

    Quote Originally Posted by jim829 View Post
    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,
    Jim
    Its the hashcode of the object, not the memory address. Java doesn't want you to worry about memory addresses remember, so why would it ever be designed to show you one anyway?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: File Out - PrintWriter

    Quote Originally Posted by gimbal2 View Post
    Its the hashcode of the object, not the memory address. Java doesn't want you to worry about memory addresses remember, so why would it ever be designed to show you one anyway?
    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.)
    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default 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

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: File Out - PrintWriter

    Quote Originally Posted by gimbal2 View Post
    Java 6 Oracle implementation just happens to be a memory address for convenience :)
    And Java 7 and Java 8. Nice spin though.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default 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

  14. #14
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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 04:07 PM.

  15. #15
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    7

    Default 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

  16. #16
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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?

  17. #17
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    7

    Default 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 06:25 PM.

  18. #18
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default 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 06:30 PM.

  19. #19
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    7

    Default 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
    }
    That is the implementation that I would choose, because in my eyes an exception is simply something exceptional. But User-Input validation is a normal check and nothing exceptional (And throwing exceptions also is an operation that takes some time.) *)

    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

  20. #20
    javaStooge is offline Senior Member
    Join Date
    Jan 2014
    Posts
    106
    Rep Power
    0

    Default Re: File Out - PrintWriter

    Thanks a lot Konrad. That explanation really helped to clarify what is going on. Finished the project and it is working perfectly.

Similar Threads

  1. File IO (PrintWriter and Methods)
    By rgru25 in forum New To Java
    Replies: 8
    Last Post: 03-14-2013, 02:38 PM
  2. Need help with PrintWriter!
    By PapaEcho in forum New To Java
    Replies: 2
    Last Post: 10-09-2011, 06:51 PM
  3. printwriter
    By sope in forum New To Java
    Replies: 2
    Last Post: 05-09-2011, 07:57 PM
  4. Help with PrintWriter code
    By eel in forum New To Java
    Replies: 4
    Last Post: 09-19-2010, 07:36 AM
  5. Help with printwriter.
    By Addez in forum New To Java
    Replies: 2
    Last Post: 10-30-2009, 01:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •