简体   繁体   中英

How to use scanner to scan txt file and put into an object array

What i have written so far works with my current knowledge of arrays but i'm just not sure about how to create the object arrays. My goal is to read a text file with the first token as the array size followed by course number, department, and title and then put them in and create an object array using a scanner. When I compile my code it says that fileScanner might not be initialized so i'm wondering what is wrong/ how i should fix my code. Any help would be mush appreciated!

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

public class Organizer{

public static void main(String[]args){
Scanner fileScanner;
String file;
File f = null;

    do{
        try{

            System.out.print("What is the name of the input file? ");
            Scanner inputReader = new Scanner(System.in);
            file =inputReader.nextLine();
            f = new File(file);
            fileScanner = new Scanner(new File(file));

        } catch (FileNotFoundException e) {

            System.out.println("Error scanning that file, please try again.");

        }
    } while (!f.exists());


    makeArray(fileScanner);

}

public static UniCourse[] makeArray(Scanner s){

        int arraySize = s.nextInt();
        System.out.println(arraySize);
        UniCourse[] myArray = new UniCourse[arraySize];
        String title = "";
        String dept = "";
        int num;

        while(s.hasNextLine()){
            String oneLine = s.nextLine();
            Scanner lineReader = new Scanner(oneLine);
            while (lineReader.hasNext()){
                dept = lineReader.next();
                num = lineReader.nextInt();
                while (lineReader.hasNext()){
                    title = title + lineReader.next();
                }

            }
            lineReader.close();
        }
        s.close();


        return myArray;

}

}

This is the class i'm using

public class UniCourse {

//INSTANCE VARIABLES
private String dept = "";
private int num = 0;
private String title = "";

//CONSTRUCTORS
public UniCourse(String dept, int num) {
    this.dept = dept;
    this.num = num; 
}

public UniCourse(String dept, int num, String title) {
    this.dept = dept;
    this.num = num; 
    this.title = title;
}

public UniCourse() {
    this.dept = "AAA";
    this.num = 100;
    this.title = "A course";    
}

//SETTER AND GETTER METHODS
public void setDept(String dept) {
    this.dept = dept;   
}

public void setNum(int num) {
    this.num = num;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDept() {
    return this.dept;   
}

public int getNum() {
    return this.num;    
}

public String getTitle() {
    return this.title;  
}

//TOSTRING METHOD
public String toString() {
    return dept + " " + num + ": "+title;
}

}

Wrap the entire do while loop AND makeArray inside the try block.

Compiler is giving the error because you only declared the scanner outside the try block, but actually initialised it inside the try block. I think anything that happens within a try block is assumed to be not there during compile time.

Error is exactly when the compiler says, you have not initialized the fileScanner when you have introduced it in code.

Try:

Scanner fileScanner = null;

You are getting that warning because your line where you do initialize it

 fileScanner = new Scanner(new File(file));

may not be reached because FileNotFoundException might be thrown. You catch that exception and continue execution, to reach the line

makeArray(fileScanner);

Where you are trying to use it. And hence the warning!

The compiler is throwing the error because you are initializing your scanner inside of a try block, which is not guaranteed to complete, and may catch and exception and break out at any point in time.

Because of this you either must initialize your scanner before the try block or add your usage of the scanner inside of your try block, so that if you catch an error before you init your scanner you don't end up using an uninitialized object.

I would suggest wrapping the make array method in the try block, as Joel suggested since you can't make the array anyway if the file doesn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM