Java error with variable initialization

In summary: If you have one big try-catch, you could only respond in a general way to all failures of any of the constructed objects.
  • #1
camel-man
76
0
Code:
import java.util.Scanner;
import java.io.FileNotFoundException; 
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class CountryPopulationReverse{

   public static void main(String args[])throws FileNotFoundException {
   
   //Variable declarations
      Scanner in = new Scanner(System.in);
      Scanner FileIn;
      FileReader inputFile;
      String population, country;
      int checkNum;
      PrintWriter output;
      boolean good = true;
      
     
      try
      {
      System.out.print("Input file: ");
      String inputName = in.nextLine();
      inputFile = new FileReader(inputName);
      FileIn = new Scanner(inputFile);
      System.out.print("Output file: ");
      String outputName = in.nextLine();
      output = new PrintWriter(outputName);
      }catch(FileNotFoundException e){ System.out.println("File not found.");}
      
     while(good)
     {
      try
      { 
      /*
      System.out.print("Input file: ");
      String inputName = in.nextLine();
      inputFile = new FileReader(inputName);
      FileIn = new Scanner(inputFile);
      System.out.print("Output file: ");
      String outputName = in.nextLine();
      output = new PrintWriter(outputName);
      */
     
      
            while(FileIn.hasNextLine())
            {
               while(!FileIn.hasNextInt())
               {
                    country = FileIn.next();
                    output.print(country);     
               }
               
               population = FileIn.next();
              
               checkNum = Integer.parseInt(population);
               output.println(checkNum);
               System.out.println(checkNum);
               if(checkNum<=5)
                   throw new BadDataException("Population (" + checkNum + ") is too low.");
               if(checkNum>2000000000)
                  throw new BadDataException("Population (" + checkNum + ") is too high.");
                 
            }
           output.close();
           good=false;
      
      } catch (FileNotFoundException e){ System.out.println("File not found.");}
        catch (BadDataException e) { System.out.println("Bad Data: " + e.getMessage());}
        catch (NumberFormatException e) { System.out.println("Number Format Exception found.");}
        
     }//End while loop
     
   }
}

Code:
CountryPopulationReverse.java:46: error: variable FileIn might not have been initialized
            while(FileIn.hasNextLine())

Not understanding java right now Why can't I declare these variables outside the try block?!?? I hate java I would rather do C it is so much more lenient.

Only time this program compiles is when I remove the innner comments of the try block and delete the top portion.
 
Technology news on Phys.org
  • #2
camel-man said:
Not understanding java right now Why can't I declare these variables outside the try block?!?? I hate java I would rather do C it is so much more lenient.

Only time this program compiles is when I remove the innner comments of the try block and delete the top portion.

Lenient isn't always good. The compiler complaints usually are there for a reason. For example, the compiler is quite right here. If that Scanner(File) call throws FileNotFoundException in the first try/catch block, you just print something in the catch part. Now, between those 2 try/catch blocks, the FileIn variable could in fact be not initialized.

And it's with that that you enter the second try/catch block. You didn't really handle the error in a good way, here. I'm going to side with the compiler on this one, I'm afraid. :)

BTW, the indentation doesn't really help make it easy to read. Good formatting and clarity are some of the key aspects of good code.
 
Last edited:
  • Like
Likes 1 person
  • #3
If by "lenient" you mean it doesn't complain, when you put a bug in your code that could cause all kinds of undefined behaviour.
I'm not entirely shure what your code is supposed to do but I'm guessing it should look more like this.

Code:
public class CountryPopulationReverse {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        Scanner FileIn = null;
        PrintWriter output = null;

        try
        {
            System.out.print("Input file: ");
            String inputName = in.nextLine();
            FileReader inputFile = new FileReader(inputName);
            FileIn = new Scanner(inputFile);
            System.out.print("Output file: ");
            String outputName = in.nextLine();
            output = new PrintWriter(outputName);
            while(FileIn.hasNextLine())
            {
               while(!FileIn.hasNextInt())
               {
                    String country = FileIn.next();
                    output.print(country);     
               }
               
               String population = FileIn.next();
              
               int checkNum = Integer.parseInt(population);
               output.println(checkNum);
               System.out.println(checkNum);
               if(checkNum<=5)
                   throw new BadDataException("Population (" + checkNum + ") is too low.");
               if(checkNum>2000000000)
                  throw new BadDataException("Population (" + checkNum + ") is too high.");
                 
            }
        } catch(FileNotFoundException e){ System.out.println("File not found.");}
          catch (BadDataException e) { System.out.println("Bad Data: " + e.getMessage());}
          catch (NumberFormatException e) { System.out.println("Number Format Exception found.");}
          finally {
            if(output != null) {
                output.flush();
                output.close();
            }
            if(FileIn != null) FileIn.close();
          }
    }
}
 
  • Like
Likes 1 person
  • #4
You can probably squelsh that error like this:

Scanner FileIn = null;

It's really warning you about something important, though. I see you are trying to do something with FileIn in your catch statement, and since the initialization of FileIn is in the try block, the catch block will not see that it has been initialized. Sure enough, it will be null, but you seem to assume it might not be at that point, and that is what the compiler is really upset about.

It is generally worthwhile to put a try-catch structure around every library call (such as initialization of a Scanner), because that specific initialization can fail. Having the try catch just for that part allows you the option to tailor an error message (or set a condition flag) for that specific failure.
 
Last edited:
  • #5


I understand your frustration with programming languages, especially when you encounter errors like this. However, it is important to understand that Java is a strictly typed language, meaning that variables must be declared and initialized before they can be used. This is to ensure that the program runs efficiently and without errors.

In this case, the variable "FileIn" is declared but not initialized before being used in the while loop. This means that there is a possibility that the program could try to use a variable that has not been given a value, which could lead to unexpected results or errors.

To fix this, you can initialize the variable at the same time as you declare it, for example:

Scanner FileIn = null;

This way, the variable has a value (in this case, null) before it is used in the while loop. You can also initialize the variable in the try block, before the while loop, to ensure that it has a value before being used.

I understand that learning a new language can be frustrating, but I encourage you to take the time to understand the rules and syntax of Java. It may seem strict, but it is designed to help you write efficient and error-free code. Keep practicing and don't give up!
 

1. What is a Java error with variable initialization?

A Java error with variable initialization occurs when a variable is not assigned a value before it is used in a program.

2. How can I fix a Java error with variable initialization?

To fix a Java error with variable initialization, make sure all variables are properly declared and assigned a value before they are used in the program.

3. What are some common causes of Java errors with variable initialization?

Common causes of Java errors with variable initialization include typos in variable names, using the wrong variable type, or forgetting to assign a value to a variable.

4. Can a Java error with variable initialization be prevented?

Yes, a Java error with variable initialization can be prevented by carefully declaring and assigning values to variables in a program.

5. Is there a specific error message for Java errors with variable initialization?

Yes, the error message will typically state that the variable has not been initialized or that it may not have been assigned a value.

Similar threads

  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
3
Views
772
  • Programming and Computer Science
Replies
2
Views
627
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
19
Views
2K
  • Programming and Computer Science
Replies
1
Views
7K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
28
Views
3K
  • Programming and Computer Science
Replies
3
Views
5K
Back
Top