Java Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesJava Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old October 29th, 2009, 11:21 PM
kairojya kairojya is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Location: Florida
Posts: 6 kairojya User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 5 m 35 sec
Reputation Power: 0
Send a message via AIM to kairojya
Homework - How to handle FileNotFoundException's?

The program basically just takes 2 integer values as parameters entered into the command line when it's ran "java assignment3 <input_number> <no_of_iterations>. Then it takes 3 integer(or double) values from the user in the command prompt, and depending on the value or <input_number> it will calculate the roots of the quadratic equation using the 3 integer values asked from the user, or calculate the y-minimum, or close. The whole process is ran in a loop according to <no_of_iterations>.

Whichever the program calculates, it outputs the results to a file "results.dat", just 3 lines of strings.

The final part of my assignment I'm confused about is handling an exception in the event the file doesn't exist. I'm not reading any data from a file in this program, only writing data to a file (with the 'true' append parameter).

I did some testing and set the file results.dat to read-only (in my Windows Vista environment) to see which error I receive, then I tried to put a catch method for that exception in my main method, after testing again it didn't seem to do what I wanted .

Code:
import java.util.Scanner;
import java.io.*;

class assignment3 {

    assignment3(int n, int g) throws IOException {

        // int n is our input_number, int g is our no_of_interations
        
        final String brk = "----------------------";

        // Listing variables used for requirements:        
        double a;
        double b;
        double c; // variable to store double entered from KBD

        // Requirement #3 addressed

        if(n == 0){
            System.out.println("Please rerun the program entering a non-zero in the command line.");
            System.exit(0);  // Quits the application
        }

        // Requirement #7 addressed

        int count = 1;
        while (count <= g) {

            // Requirement #4 addressed

            Scanner in = new Scanner(System.in);
            System.out.print("Please enter a coefficient: ");
            a = Double.parseDouble(in.nextLine());
            System.out.print("Please enter a coefficient: ");
            b = Double.parseDouble(in.nextLine());
            System.out.print("Please enter a coefficient: ");
            c = Double.parseDouble(in.nextLine());

            // Requirement #1 addressed

            if(n > 0){
                double root1 = (-b + Math.sqrt(b*b-4*a*c))/(2*a);
                double root2 = (-b - Math.sqrt(b*b-4*a*c))/(2*a);

                // Requirement #5 addressed

                PrintWriter out = new PrintWriter(new FileWriter("results.dat", true));
                out.println("Quadratic equation with the following coefficients:");
                out.println("a: " + a + ";" + " b: " + b + ";" + " c: " + c + ";");
                out.println("has the following roots: " + root1 + " and " + root2);
                out.println(brk);
                out.close();  // Closing a file after writing to it.

                boolean b1 = Double.isNaN(root1);
                boolean b2 = Double.isNaN(root2);

                if(b1 || b2) {
                    System.out.println(" ");
                    System.out.println("Quadratic equation with the following coefficients:");
                    System.out.println("a: " + a + ";" + " b: " + b + ";" + " c: " + c + ";");
                    System.out.println("does not have roots in the real domain.");
                }
            }

            // Requirement #2 addressed

            if (n < 0){
                double y=0; //For finding ymin
                double x=0; //For finding ymin

                //Use quadratic functions derivative to find xmin, a*x+b=0
                x = -b/(2*a);
                //Use xmin in original quadratic equation to find ymin value:
                y = (a*(x*x)+b*x+c);

                // Requirement #6 addressed

                PrintWriter out = new PrintWriter(new FileWriter("results.dat", true));
                out.println("Quadratic equation with the following coefficients:");
                out.println("a: " + a + ";" + " b: " + b + ";" + " c: " + c + ";");
                out.println("has the following minimum: " + y + " at point " + x);
                out.println(brk);
                out.close();  // Closing a file after writing to it.

                boolean y1 = Double.isNaN(y);

                if(y1) {
                    System.out.println(" ");
                    System.out.println("Quadratic equation with the following coefficients:");
                    System.out.println("a: " + a + ";" + " b: " + b + ";" + " c: " + c + ";");
                    System.out.println("does not have a minimum.");
                }
            }
            count++;
        }
    }

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

        // Requirement #0 addressed

        try {
            new assignment3(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("No parameters in the command line entered; default values of 1 assumed.");
            new assignment3(1, 1);
        }
        catch (NumberFormatException e) {
            System.out.println("Please only enter integers into the command line next time.");
            System.out.println("System Exiting.");
            System.exit(0);
        }
        catch (FileNotFoundException e){
            System.out.println("The file \"results.dat\" doesn't exist, or is read-only.");
            System.out.println("System Exiting.");
            System.exit(0);
        }
   }
}


Keep in mind this is my first semester ever experiencing this programming language, and I'm sure there's a lot of different and easier ways I could have wrote this application . The comments in the code are required in my class.

I'd like to know of any method I could use to maybe remove the read-only attribute of the file, or just any ideas you guys have on what I'm doing wrong.

Reply With Quote
  #2  
Old October 29th, 2009, 11:49 PM
tvc3mye's Avatar
tvc3mye tvc3mye is offline
Daniel Schildsky
Dev Shed Novice (500 - 999 posts)
 
Join Date: Mar 2004
Location: KL, Malaysia.
Posts: 955 tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level) 
Time spent in forums: 1 Week 3 Days 4 h 16 m 27 sec
Reputation Power: 542
Send a message via ICQ to tvc3mye Send a message via MSN to tvc3mye Send a message via Yahoo to tvc3mye
Handling Errors

You do not have to keep on opening and closing the file in a while loop. Simply remove the file opening and closing statement out of the loop. Open the file before the while loop and then close the file after the loop is completed.

Also, why handle FileNotFoundException if you are not reading from a file? You only have to do so if you are writing to an existing file. In that case, you open an existing file, append to the file or overwrite the contents in that file, then close it. Should you encounter the FileNotFoundException, just create the file and continue with the rest of the code.
Comments on this post
jzd agrees!
__________________
When the programming world turns decent, the real world will turn upside down.

Reply With Quote
  #3  
Old October 30th, 2009, 01:11 AM
kairojya kairojya is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Location: Florida
Posts: 6 kairojya User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 5 m 35 sec
Reputation Power: 0
Send a message via AIM to kairojya
Quote:
Originally Posted by tvc3mye
You do not have to keep on opening and closing the file in a while loop. Simply remove the file opening and closing statement out of the loop. Open the file before the while loop and then close the file after the loop is completed.


Yea thanks for the heads up, forgot about that >_<;

Quote:
Originally Posted by tvc3mye
Also, why handle FileNotFoundException if you are not reading from a file? You only have to do so if you are writing to an existing file. In that case, you open an existing file, append to the file or overwrite the contents in that file, then close it. Should you encounter the FileNotFoundException, just create the file and continue with the rest of the code.


I asked my instructor this exactly before I posted this. This is the response he gave me:

Quote:
1) When you create a file, there is no guarantee that there is enough space on the disk for this file to be cretaed. Thus, a professionally written program has to take this into account.
2) Even if you create a file successfully, you may do other calculations then, for a long while, before you write to this file. In this interval, between file creation and an attempt to write to a file, something may happen which will make this file disappear. For example, it may be deleted by your own program (incidentally, by a method that may be executed prematurely), or by another program that uses the same file.


So if I leave any of these possible exceptions out, I'll surely loose points on my assignment .

Reply With Quote
  #4  
Old October 31st, 2009, 01:13 AM
tvc3mye's Avatar
tvc3mye tvc3mye is offline
Daniel Schildsky
Dev Shed Novice (500 - 999 posts)
 
Join Date: Mar 2004
Location: KL, Malaysia.
Posts: 955 tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level)tvc3mye User rank is Colonel (50000 - 60000 Reputation Level) 
Time spent in forums: 1 Week 3 Days 4 h 16 m 27 sec
Reputation Power: 542
Send a message via ICQ to tvc3mye Send a message via MSN to tvc3mye Send a message via Yahoo to tvc3mye
File deleted by premature call to methods?

For the first point given by your lecturer, I would say, you simply catch an IOException and handle that situation to recover from it.

However, for the second opinion, I do not think that would occur to your program, since your program does not feature multithreading which might perform operations concurrently. Besides, JVM file creates a write lock on the file that you are going to write on. However, this might be O/S specific, which I am not sure about. If someone does have information on this, perhaps he/she should share it here.
Comments on this post
kairojya agrees: ty for the help

Reply With Quote
  #5  
Old November 1st, 2009, 09:22 PM
kairojya kairojya is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2009
Location: Florida
Posts: 6 kairojya User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 5 m 35 sec
Reputation Power: 0
Send a message via AIM to kairojya
Quote:
Originally Posted by tvc3mye
For the first point given by your lecturer, I would say, you simply catch an IOException and handle that situation to recover from it.

However, for the second opinion, I do not think that would occur to your program, since your program does not feature multithreading which might perform operations concurrently. Besides, JVM file creates a write lock on the file that you are going to write on. However, this might be O/S specific, which I am not sure about. If someone does have information on this, perhaps he/she should share it here.


Ah good points, thanks for the help. Hopefully I get a decent grade, we'll see.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesJava Help > Homework - How to handle FileNotFoundException's?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump




 Free IT White Papers!
 
How to Present Effectively Online
This white paper offers practical and actionable advice on the key steps that any presenter should consider as they plan and execute a Webinar or online meeting.

 
Open Source Security Myths
Open Source Software (OSS) is computer software whose source code is available to the general public with relaxed or non-existent intellectual property restrictions (or arrangement such as the public domain), and is usually developed with the input of many contributors.

 
Power and Cooling Capacity Management for Data Centers
This paper describes the principles for achieving power and cooling capacity management.

 
Scalable, Fault-Tolerant NAS for Oracle - The Next Generation
For several years NAS has been evolving as a storage alternative for Oracle databases, and for good reason: NAS is quite often the simplest, most cost-effective storage approach for Oracle. Learn about the benefits that HP's approach to scalable NAS brings to Oracle environments in this comprehensive white paper.

 
Understanding Web Application Security Challenges
This white paper discusses many common threats and preventive measures for Web application security, and explains what you can do to help protect your organization.

 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 




© 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
For more Enterprise Application Development news, visit eWeek