0

In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:

Inside the TestSubject class -

//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();

//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();

//add records to the file
subject.addRecords(subjectName, subjectCode);

Inside the subject class -

//add the records of valid subject name and subject code    
public void addRecords(String name, String code) {
    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
        out.printf(name);
        out.printf("\n");
        out.printf(code);
        out.printf("\n");
        out.close();
    }catch (IOException e) {

    }
}

I then want to read this file and pass the data through to an arraylist. The file might look something like:

Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789

I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.

//read data from subjects file and place in an array
public void readData(){
    Scanner input = new Scanner("subjects.txt");
    while (input.hasNext()) {
        String subjectName = input.nextLine();
        String subjectCode = input.nextLine();
    }

    ArrayList<String> subjectNames = new ArrayList<String>();
    ArrayList<String> subjectCodes = new ArrayList<String>();

    //add the input to the arrays

    subjectNames.add(subjectName);
    subjectNames.add(subjectCode);

    //display the contents of the array

    System.out.println(subjectNames.toString());
    System.out.println(subjectCodes.toString());
}

Even if there is a good tutorial around that I might be able to be pointed in the right direction...

JavaNube
  • 39
  • 5
  • 4
    and what is your question? – Alexandre Santos May 18 '14 at 00:56
  • 1
    Agree with @AlexandreSantos. I see an `"I want..."`, but no specific question. What have you tried? How isn't it working? Where ***exactly*** are you stuck? – Hovercraft Full Of Eels May 18 '14 at 00:57
  • 2
    I wonder if you're coming here too early. What you need to do is to try to solve your problem first, and then if still suck, show your code attempt and describe in details what is wrong with it. As an aside, your `catch` block should most definitely not be empty. At the very least give it a `e.printStackTrace()` call. – Hovercraft Full Of Eels May 18 '14 at 01:05
  • I have shown what I was trying to do. I think a tutorial if there is one available somewhere might be handy – JavaNube May 18 '14 at 01:12

2 Answers2

1

Thanks for editing your post. Much easier to help when I can see what's causing problems.

You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.

You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.

The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.

Give "Reading a plain text file in Java" a read.

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62
0

Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:

public static void main(String[] args){

ArrayList<String> subjectNames = new ArrayList<String>();
     ArrayList<String> subjectCodes = new ArrayList<String>();

    //Path leading to the text file
    Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");

    int count = 0;//Will indicate which list to add the current line to

    //Create a buffered reader to read in the lines of the file
    try(BufferedReader reader  = new BufferedReader(new FileReader(data.toFile()))){
        String line = "";
        while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
            count++;//Increment number changing from odd to even or vice versa
            if(count % 2 == 0){//If number is even then add to subject codes
                subjectCodes.add(line);
            } else {//Otherwise add to subject names
                subjectNames.add(line);
            }
        }
    } catch (IOException io){
        System.out.println("IO Error: " + io.getMessage());
    }

    System.out.println("Codes: ");
    display(subjectCodes);
    System.out.println("\nNames: ");
    display(subjectNames);


}


private static void display(Collection<String> c){
    for(String s :c){
        System.out.println(s);
}

Hope it helps!

Levenal
  • 3,796
  • 3
  • 24
  • 29
  • I'd recommend starting count at 0 and incrementing it at the end of the loop. Won't change the modulo logic used now since it shaves 2 off the count. But if he ever tries to add a 3rd line it'd be nice if count didn't magically start at 2. – candied_orange May 18 '14 at 02:04
  • Fair point, can't remember why I started it at 1, answer re-jigged :) – Levenal May 18 '14 at 02:19
  • You forgot to move the count++ to the end of the loop. Now it's magically starting at 1. Swapping the codes to the top of the loop like you have fixes the bug but it is incredibly counter intuitive. Again I recommend incrementing at the bottom of the loop. Remember modular division (%) is inherently zero indexed. So the 'count' should be as well. Start at zero and keep the add's in the same order they are found in the file simply for the sake of readability. – candied_orange May 18 '14 at 04:27