Alright, I'm trying to import data from a text file into an array, the data represents different properties of buildings that are to be drawn on a panel. I have 3 classes, Building3 which represents an individual building, CityPanel3 which represents the panel that the buildings are drawn upon (also where i try importing the data into the array), and NightCity3 which has the main method and adds the panel to a frame.
When i try and compile my CityPanel3 class, i keep getting an excepion stating "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" at the line of code "Scanner scan = new Scanner(new File("buildingData.txt"));
I try adding simple Try and Catch block statements and only get 30 something more errors that make no sense (They make no sense because this program works with an arrayList without importing data from a file) However, i need to do it in a way of importing the data from a text file.

Any help would be greatly appreciated

Here iss the code that i have so far of the 3 classes (CityPanel3 is the one where the exception is occuring)

import java.awt.*;
import java.util.*;

public class Building3
{
    private int width, height, x;
    private Color color;

    public Building3(int wWidth, int hHeight, int upperX, Color shade)
    {
        width = wWidth;
        height = hHeight;
        x = upperX;
        color = shade;      
    }

    public void draw (Graphics page)
    {
        page.setColor (color);
        page.fillRect (x, 420 - height, width, height);
        drawWindows (page);
    }
    
        public void setWidth (int wWidth)
    {
        width = wWidth;
    }
    
        public void setHeight (int hHeight)
    {
        height = hHeight;
    }
    
        public void setColor (Color shade)
    {
        color = shade;
    }
    
        public void setX (int upperX)
    {
        x = upperX;
    }
    
        public int getWidth ()
    {
        return width;
    }
    
        public int getHeight ()
    {
        return height;
    }
    
        public Color getColor ()
    {
        return color;
    }
    
        public int getX ()
    {
        return x;
    }
    
    public void drawWindows(Graphics page)
    { 
        page.setColor(Color.yellow); 
        Random generator = new Random(); 
        int rand = generator.nextInt(6) + 2; 
        int numWindows = 0; 
        int windowSize = 20;
        int y1 = (420 - height);
        int startingY = (y1 + 10);
        while (numWindows <= rand && startingY < 390) 
        { 
            int x1 = x;
            int xRand = generator.nextInt(width - 40) + (x1 + 10);
            
            page.fillRect(xRand, startingY, windowSize, windowSize);
            numWindows++;
            startingY = startingY + (windowSize + 10);
            
        } 
    }        
}


import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;

public class CityPanel3 extends JPanel
{
private Building3 temporaryBuildings;
private Color gray = new Color (128,128,128);

      String line;
      Scanner scanToken;
      Scanner scan = new Scanner(new File("buildingData.txt"));
      Building3[] buildingList = new Building3[7]; 
      int width; 
      int height;
      int x;
      Color color;
      int cValue;
      int size = 0;
      Scanner choose = new Scanner (System.in);

public CityPanel3 ()
{
  //*************************************************
  // Parallel arrays assignvalues to the array list
  //*************************************************
   while (scan.hasNext())
      {
      line = scan.nextLine();
      scanToken = new Scanner(line);
      scanToken.useDelimiter(" "); 
      width = scanToken.nextInt();
      height = scanToken.nextInt();
      x = scanToken.nextInt();
      cValue = scanToken.nextInt();
      color = new Color (cValue,cValue,cValue);
      buildingList[size] = new Building3 (width, height, x, color);
      size++;  
  }
  setPreferredSize (new Dimension(800,500));
  setBackground (Color.black);
}

public void paintComponent (Graphics page)
{
  super.paintComponent(page);
  for(int count=0;count<7;count++)
  {
   buildingList[count].draw(page);
  }
}
}


import javax.swing.*;
import java.awt.*;

public class NightCity3
{
    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("NightCity3");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        
        frame.getContentPane().add(new CityPanel3());
        
        frame.pack();
        frame.setVisible(true);
    }    
}

Thanks again for any help

Recommended Answers

All 6 Replies

Oh yeah, i also forgot to mention that no, its not an invalid file name or path. That was the first thing that i checked. The file im trying to import in my code is in the correct folder, and is spelled correctly.

You need to declare the FileNotFoundException in the signature of any constructors, because any variables that are initialized in the field declaration, is like it being initialized in the constructor (before the body of the constructor is executed).

public CityPanel3() throws FileNotFoundException {
...
}

You cannot surround it with a try-catch block, since it is not in a method. Also, if you make any more constructors, make sure to add the throws statement at the end.

I should also mention, that if you did want to use a try-catch block (i.e. handle the exception in the constructor) then leave the field declaration as Scanner scan; and initialize the field in the constructor.

thanks alot! all i had to do was place "throws FileNotFoundException" at that constructor as well as after the main method in my NightCity3 class, and everything compiles correctly and does what i intended it to do!

I know this is marked as solved, but I think that's wrong - it's not solved, just ignored! By placing the "throws" clauses like that the program has specified that, if there is any problem locating a file, it will terminate immediately without any error message. That can't be a good thing to do. It should catch the exception somewhere (eg maybe the first method throws it, but the second catches it) and issue some kind of diagnostic message so the poor user (and the poor developer supporting him) isn't left baffled and in the dark as to why the program just vanished.

I know this is marked as solved, but I think that's wrong - it's not solved, just ignored! By placing the "throws" clauses like that the program has specified that, if there is any problem locating a file, it will terminate immediately without any error message. That can't be a good thing to do. It should catch the exception somewhere (eg maybe the first method throws it, but the second catches it) and issue some kind of diagnostic message so the poor user (and the poor developer supporting him) isn't left baffled and in the dark as to why the program just vanished.

This is absolutely correct. A good programmer keeps complete track of the flow. The throws clause is alright in class CityPanel3, but don't use it for main(). Instead, while initializing the object of citypanel3, catch that exception.

Another problem that u induce by not catching the exception is allowing an unkown stack trace to flow into the logic. In case you log your application, the jvm would create a stack trace for you but you would never be able to tell where to actually look at as everywhere you just shed your responsibility.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.