943,781 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 1277
  • Java RSS
You are currently viewing page 1 of this multi-page discussion thread
May 12th, 2009
0

Accessing declared String objects outside Try-Catch Blocks.

Expand Post »
Hello, I seem to have encountered a problem with this code.

java Syntax (Toggle Plain Text)
  1. try
  2. {
  3. String changeC1 = JOptionPane.showInputDialog (null, "Change the dimensions of silo 1? (y/n)");
  4. }
  5. catch (NullPointerException e)
  6. {
  7. String changeC1 = "n"; // probably also be a good idea to log the fact an exception occured.
  8. }
  9. try
  10. {
  11. String changeC2 = JOptionPane.showInputDialog (null, "Change the dimensions of silo 2? (y/n)");
  12. }
  13. catch (NullPointerException e)
  14. {
  15. String changeC2 = "n";
  16. }
  17.  
  18. [COLOR="red"] if (changeC1.equalsIgnoreCase("y") && changeC2.equalsIgnoreCase("y"))[/COLOR]
  19. {
  20. changeDimensionsOne(iRadius, iHeight, c1, MAX);
  21. changeDimensionsTwo(iRadius, iHeight, c2, MAX);
  22. displayDimensions(c1, c2);
  23. }
  24.  
  25. else if (changeC1.equalsIgnoreCase("y"))
  26. {
  27. changeDimensionsOne(iRadius, iHeight, c1, MAX);
  28. displayDimensions(c1, c2);
  29. }
  30. else if (changeC2.equalsIgnoreCase("y"))
  31. {
  32. changeDimensionsTwo(iRadius, iHeight, c2, MAX);
  33. displayDimensions(c1,c2);
  34. }
  35.  
  36. }
I am assuming this is because the String object is inside a catch block. How do I make it so that my if statement can recognise it?

Thanks for any help!
Last edited by AirmanTheGreat; May 12th, 2009 at 3:53 am.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
AirmanTheGreat is offline Offline
21 posts
since Aug 2008
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

I guess you have a pretty clear idea of what is happening around here. So I just would like to give you the notion of why it happens.

When you declare a variable inside a method or more appropriately a block, the variable falls out of scope at the '}' (closing brace) for the block, which means as soon as the block ends. Since you declare the variables change1 and change2 inside the try block, these variabels would fall out of scope as soon as the try block ends. Naturally a variable which has fell out of scope cannot be accessed and that would explain the cause of the error.

So you need to do something like this:
java Syntax (Toggle Plain Text)
  1. String change1, change2;
  2. try{
  3. // try some code here
  4. }
  5. catch{
  6. //catch some exception here
  7. }
  8.  
  9. if (change1.equals("whatever") && change2.equals("whatnot")){
  10. // whatever and whatnot code
  11. }
Reputation Points: 485
Solved Threads: 89
Posting Shark
verruckt24 is offline Offline
944 posts
since Nov 2008
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

Hello AirManTheGreat,

I suggest you declare the String objects changeC1 and changeC2 outside, before all those try blocks and stuff.
Then only the if blocks outside those try and catch can access these variables

Regards,
SNIP
Last edited by happygeek; May 12th, 2009 at 7:06 am. Reason: fake sig snipped
Reputation Points: 10
Solved Threads: 1
Newbie Poster
nabeel.alsafa is offline Offline
5 posts
since May 2009
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

Well i think verrukt24 has made it clear for u.. TRY that :-)

Regards,
SNIP
Last edited by happygeek; May 12th, 2009 at 7:06 am. Reason: fake sig snipped
Reputation Points: 10
Solved Threads: 1
Newbie Poster
nabeel.alsafa is offline Offline
5 posts
since May 2009
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

Thanks for the quick response

I thank you for your advice, and I have corrected the placement of the declaration of the String objects,

However now it appears the try-catch block is not working.
The purpose of putting the try-catch blocks was to catch a NullPointerException error (that is, if the user hit cancel), the code runs fine until it hits the if statement and then it crashes due to a NullPointerException, even though i have declared in the catch block that in the event of NullPointerException, the String object should alter to = "n" (thus preventing a crash). I added an else statement after the if's to simply exit the program if this was the case. I do not understand why the try-catch block is not working

EDIT: I did a quick debug of it, it appears when the user hits cancel, it skips the catch block, that is, it assigns null value to string rather than "n" as I put in the catch block?
Last edited by AirmanTheGreat; May 12th, 2009 at 4:50 am.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
AirmanTheGreat is offline Offline
21 posts
since Aug 2008
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

Even if the user hits the cancel button you won't get a NullPointerException. If the user clicks cancel you would get an in value specifying that the user hit the cancel option. So just fetch the value in an int and compare it to JOptionPane.CANCEL_OPTION, and write your code depending on that.

Check the JOptionPane class for information
Reputation Points: 485
Solved Threads: 89
Posting Shark
verruckt24 is offline Offline
944 posts
since Nov 2008
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

I have checked the link you specified, I am still unsure as to how it works. Can you please give me a small example of how it works?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
AirmanTheGreat is offline Offline
21 posts
since Aug 2008
May 12th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

int value = JOptionPane.showMessageDialog(null,"blah");

if(value == JOptionPane.CANCEL_OPTION){
//do stuff
}
Reputation Points: 874
Solved Threads: 352
Posting Maven
BestJewSinceJC is offline Offline
2,758 posts
since Sep 2008
May 13th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

Now I get an error - Found java.lang.string but expected int?

Here is the code

/**
 * Driver program - Creates silo objects, asks for user input on dimensions of silo - returns results of size dimensions
 * 
 * @author (Luke Schmid) 
 * @version (1)
 */
import javax.swing.*;
public class siloTest
{
    final static int MAX = 0;
    final static double pi = 22.0/7;
    public static final int CANCEL_OPTION =0 ;
    
    public static void main (String[]args)
    {
        //creates two seperate 'silo' objects.
        silo c1 = new silo();

        

        //Create MAX int for input comparison.
        
        
        //sets iRadius to 0 to initialize while loop
        double iRadius = 0;
        while (iRadius <= MAX) 
            {
                String pRadius1 = JOptionPane.showInputDialog(null, "Enter radius of Silo: 1");
                try
                {
                    iRadius = Double.parseDouble(pRadius1);
                    //set radius of c1 'silo' object
                    c1.setRadius(iRadius);
                }
                
                catch (NumberFormatException nfe)
                {

                    iRadius = -1; // just to be safe
                }
                //Stops programming from crashing if user presses Cancel button
                catch (NullPointerException e)
                {
                    System.exit(0);
                }
                 
                //determines whether loop will execute again
                if (iRadius <= MAX)
                JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);

            }
        
        //Sets iHeight to 0 to intialize loop
        double iHeight = 0;
        while (iHeight <= MAX) 
        {
            String pHeight1 = JOptionPane.showInputDialog(null, "Enter the height of Silo: 1");
            try
               {
                   iHeight = Double.parseDouble(pHeight1);
                   c1.setHeight(iHeight);
               }
                   
            catch (NumberFormatException nfe)
               {

                   iHeight = -1; //just to be safe
               }
            //Stops programming from crashing if user presses Cancel button
            catch (NullPointerException e)
               {
                    System.exit(0);
               }
            //determines whether loop will continue
            if (iHeight <= MAX)
            JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);
               
        }
        
        //iRadius has been succesfully set in the above code, so it needs to be reset to 0 here to again start the loop
        iRadius = 0;
        while (iRadius <= MAX) 
            {
                String pRadius2 = JOptionPane.showInputDialog(null, "Enter radius of Silo: 2");
                try
                {
                    iRadius = Double.parseDouble(pRadius2);

                }
                
                catch (NumberFormatException nfe)
                {

                    iRadius = -1; //just to be safe
                }
                //Stops programming from crashing if user presses Cancel button
                catch (NullPointerException e)
                {
                    System.exit(0);
                }
                //Determines whether loops starts again
                if (iRadius <= MAX)
                JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);
                    

            }
         //Same story as iRadius   
         iHeight = 0;
         while (iHeight <= MAX)   
         {
            String pHeight2 = JOptionPane.showInputDialog(null, "Enter the height of Silo: 2");
            try
               {
                   iHeight = Double.parseDouble(pHeight2);
           
               }
                   
            catch (NumberFormatException nfe)
               {

                   iHeight = -1; //to be safe
               }
               //Stops programming from crashing if user presses Cancel button
            catch (NullPointerException e)
               {
                   System.exit(0);
               }
            //determines whether loop will start again or not   
            if (iHeight <= MAX)
            JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);

        }
            silo c2 = new silo(iRadius, iHeight);  
            displayDimensions(c1, c2);
            
            
            
            
            
            String changeC1, changeC2;
            
            int value = JOptionPane.showInputDialog (null, "Change the dimensions of silo 1? (y/n)");            
            if (value == JOptionPane.CANCEL_OPTION)
            {
                changeC1 = "n";
            }
            
            int value2 = JOptionPane.showInputDialog (null, "Change the dimensions of silo 2? (y/n)");
            
            if (value == JOptionPane.CANCEL_OPTION)
            {
                changeC2 = "n";
            }
            
            
            
            

            

            if (changeC1.equalsIgnoreCase("y") && changeC2.equalsIgnoreCase("y"))

            {
                changeDimensionsOne(iRadius, iHeight, c1, MAX);
                changeDimensionsTwo(iRadius, iHeight, c2, MAX);
                displayDimensions(c1, c2);
            }
            
            else if (changeC1.equalsIgnoreCase("y"))
            {
                changeDimensionsOne(iRadius, iHeight, c1, MAX);
                displayDimensions(c1, c2);
            }
            else if (changeC2.equalsIgnoreCase("y"))
            {
                changeDimensionsTwo(iRadius, iHeight, c2, MAX);
                displayDimensions(c1,c2);
            }
            else
            System.exit(0);
        
   
    }  

      

        
        
    
    public static void displayDimensions(silo c1, silo c2)
    {
        JOptionPane.showMessageDialog(null, "Silo 1\nRadius = " + c1.getRadius() + 
                                            "\nHeight = " + c1.getHeight() +
                                            "\nSurface Area = " + c1.getSurfaceArea(pi) +
                                            "\nVolume = " + c1.calcVolume(pi));
        
        JOptionPane.showMessageDialog(null, "Silo 2\nRadius = " + c2.getRadius() + 
                                            "\nHeight = " + c2.getHeight() +
                                            "\nSurface Area = " + c2.getSurfaceArea(pi) +
                                            "\nVolume = " + c2.calcVolume(pi));
        
    }
    public static void changeDimensionsOne(double iRadius, double iHeight, silo c1, int MAX)
    {
     iRadius = 0;
     while (iRadius <= MAX) 
            {
                String pRadius1 = JOptionPane.showInputDialog(null, "Enter radius of Silo: 1");
                try
                {
                    iRadius = Double.parseDouble(pRadius1);
                    //set radius of c1 'silo' object
                    c1.setRadius(iRadius);
                }
                
                catch (NumberFormatException nfe)
                {

                    iRadius = -1; // just to be safe
                }
                //Stops programming from crashing if user presses Cancel button
                catch (NullPointerException e)
                {
                    System.exit(0);
                }
                 
                //determines whether loop will execute again
                if (iRadius <= MAX)
                JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);

            }
        
        //Sets iHeight to 0 to intialize loop
        iHeight = 0;
        while (iHeight <= MAX) 
        {
            String pHeight1 = JOptionPane.showInputDialog(null, "Enter the height of Silo: 1");
            try
               {
                   iHeight = Double.parseDouble(pHeight1);
                   c1.setHeight(iHeight);
               }
                   
            catch (NumberFormatException nfe)
               {

                   iHeight = -1; //just to be safe
               }
            //Stops programming from crashing if user presses Cancel button
            catch (NullPointerException e)
               {
                    System.exit(0);
               }
            //determines whether loop will continue
            if (iHeight <= MAX)
            JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);
               
        }   
    }

    
    public static void changeDimensionsTwo(double iRadius, double iHeight, silo c2, int MAX)
    {
                iRadius = 0;
        while (iRadius <= MAX) 
            {
                String pRadius2 = JOptionPane.showInputDialog(null, "Enter radius of Silo: 2");
                try
                {
                    iRadius = Double.parseDouble(pRadius2);

                }
                
                catch (NumberFormatException nfe)
                {

                    iRadius = -1; //just to be safe
                }
                //Stops programming from crashing if user presses Cancel button
                catch (NullPointerException e)
                {
                    System.exit(0);
                }
                //Determines whether loops starts again
                if (iRadius <= MAX)
                JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);
                    

            }
         //Same story as iRadius   
         iHeight = 0;
         while (iHeight <= MAX)   
         {
            String pHeight2 = JOptionPane.showInputDialog(null, "Enter the height of Silo: 2");
            try
               {
                   iHeight = Double.parseDouble(pHeight2);
           
               }
                   
            catch (NumberFormatException nfe)
               {

                   iHeight = -1; //to be safe
               }
               //Stops programming from crashing if user presses Cancel button
            catch (NullPointerException e)
               {
                   System.exit(0);
               }
            //determines whether loop will start again or not   
            if (iHeight <= MAX)
            JOptionPane.showMessageDialog (null, "Please enter a number higher than 0.\nAlso ensure you are entering an integer", "Error!", JOptionPane.ERROR_MESSAGE);

        }
            c2.setRadius(iRadius);
            c2.setHeight(iHeight);
                               
            
    }  
    }
Reputation Points: 10
Solved Threads: 0
Newbie Poster
AirmanTheGreat is offline Offline
21 posts
since Aug 2008
May 13th, 2009
0

Re: Accessing declared String objects outside Try-Catch Blocks.

change "showInputDialog" to "showMessageDialog" on the line where you have your error. And this thread is starting to get unwieldy; if you have solved your original problem, you should mark it as solved and post a new thread explaining whatever problems you are currently having. Also, when you use the code tags, the first one should say [CODE=Java] (this will give prettier formatting and also will give line numbers)
Last edited by BestJewSinceJC; May 13th, 2009 at 1:43 am.
Reputation Points: 874
Solved Threads: 352
Posting Maven
BestJewSinceJC is offline Offline
2,758 posts
since Sep 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: Help: iCal/vCal export
Next Thread in Java Forum Timeline: Reverse Numbers Using An Array.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC