-2

`import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;

public class Dokimi {

private static String line;


public static void  main (String[] args) throws IOException


{

    int x = 0;
    BufferedReader br = new BufferedReader(new FileReader("src/film.txt"));
    line = br.readLine();

    String[] filmline = new String [1000];

    while (line != null) {
        line = br.readLine();
        filmline[x] = line;
        x++;

    }
    br.close();

    for (int i = 0; i<x; i++) // after many tries the last change I made is this. This is the testing class.
    {

        String [] arr = filmline[i].split(": ");


        if ( i == x-1) // I know it isn't the best, maybe not even good but I tried many things and had nothing to lose.

        {

            for ( String ss : arr) {

                   String test = ss;
                    if (test.equals("Dancing With The Dogs "))
                    {
                        System.out.println("gotcha!");

                    }

                }

        }
    }






}

}`So, I have a text file with the attributes of some movies. For example :

"film id :  1  film title :   Pirates Of Hawai  film category :   action ,      comedy   film description :  A pirate from Hawai drinks rum and goes on an adventure to find more rum." 

(every entry in one line) and each time a user is trying to add a new entry I have to make sure the film isn't already on the file. I tried the slpit method (by using ":" and erasing "film id" etc) and StringTokenizer but it only worked on ONE and specified by me line, and not in a loop so that it could read the whole file.

Unknown
  • 13
  • 4
  • First create a program that reads each line from the file and prints it, just so you know it works. Then improve that program to do the comparison you need. And then improve it to also save the information to a file. Always break a programming task into small steps. – RealSkeptic Jun 05 '15 at 11:10
  • Can you change your approach to XML file or maybe a Database? I am assuming you are doing a class exercise your teacher asked you. – Solano Jun 05 '15 at 11:10
  • @RealSkeptic I did this and as I said it only encouters problems when it gets in the loop it sometimes manages to break the first line and then stops or it doesn't work at all... if I specify which line I want it to break it works just fine but the thing is I need to do it on the whole file. – Unknown Jun 05 '15 at 11:20
  • @Solano yes it is an assignment and it is the first time I had to do complicated things with files in Java and I am trying to find how to do all that through the internet since I don't have much knowledge over files yet. – Unknown Jun 05 '15 at 11:20
  • If you did write a loop like that, and it has problems, then please add its code to your question - properly formatted with the `{}` button, and please make sure it's properly formatted by using your IDE format source option before copying it. With the source in the question, and an explanation of the problem and errors you get, we might be able to help. – RealSkeptic Jun 05 '15 at 11:21

2 Answers2

0

Don't use StringTokenizer, it's legacy, and should be supported for maintenance reasons, but not be implemented in new code.

Considering the tokens differ each time, you may want to run over the String and using substring here and there, that is, assuming each line contains the same tokens.

Or, change your input in:

"1*Pirates Of Hawaiaction , comedyA pirate from Hawai drinks rum and goes on an adventure to find more rum."

This way, all tokens are identical, and you will be able to use the split method.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • I tried it like " 1 : Pirates Of Hawai : action , comedy : A pirate from Hawai drinks rum and goes on an adventure to find more rum. " and it works just fine when I use it on a specified line but when I try it on a loop it won't work – Unknown Jun 05 '15 at 11:11
  • @Unknown: if it works on one line, it works on all, even in a loop. What is it that doesn't work ? – Stultuske Jun 05 '15 at 11:12
  • every time I use split inside a loop I encounter this : "Exception in thread "main" java.lang.NullPointerException " which is located in the line the split method is inside the loop – Unknown Jun 05 '15 at 11:14
  • that means you are calling split on a null. re-check your input file, most likely, there's an empty line at the end – Stultuske Jun 05 '15 at 11:16
  • I checked the file and there is no empty line anywhere. – Unknown Jun 05 '15 at 11:23
  • You'll need to add more information (the actual contents of the file, the exact stacktrace, .. – Stultuske Jun 05 '15 at 11:41
  • I edited the question to have the code ( well at least the last saved one for that matter ) if it makes it easier – Unknown Jun 05 '15 at 11:44
  • Not really. we still don't know the exact input, or error. is it possible there is a line with one (or more) tokens less ? – Stultuske Jun 05 '15 at 11:45
  • at this point all I am trying to do is read from the film.txt which has the entries in the "film id : 1 film title : Pirates Of Hawai film category : action , comedy film description : A pirate from Hawai drinks rum and goes on an adventure to find more rum." format until I make the program able to at least run there is no point in asking user input ( Dancing with the Dogs is an entry in the file ) – Unknown Jun 05 '15 at 11:49
  • short summary: 1. make sure all the tokens are the same, so not "film id" and "film title", just a separator (like *) between all the tokens. 2. make sure all the lines have the same amount of tokens so, not: title*genre*description on one line and just title on another. – Stultuske Jun 05 '15 at 11:54
  • I checked the text file again and again and it follows these principals each movie's tokens are in one line.. what is changed from the original format is that now the indicators are missing and every entry is like : " 1 : Pirates Of Hawai : action , comedy : A pirate from Hawai drinks rum and goes on an adventure to find more rum." (all in one line) to work better with the split. – Unknown Jun 05 '15 at 12:01
0

As per here

Change your line a bit to add a ":":

"film id :  1 : film title :   Pirates Of Hawai : film category :   action ,      comedy :  film description :  A pirate from Hawai drinks rum and goes on an adventure to find more rum." 

You can try this approach and compare with yours: (use existsfilm to verify if it already exists before add)

 public void showAllFilms(){
    ArrayList<String[]> films = getFilms();
    for(String[] film : films){
        System.out.println("id "+film[0]+"\ntitle "+film[1]);
    }
 }

 public existsFilm(String filmName){
     ArrayList<String[]> films = getFilms();
     for(String[] film : films){
         if(film[1].equals(filmName)){
           return true;
         }
     }
     return false;
 }

 public ArrayList<String[]> getFilms(){
    ArrayList<String[]> filmList = new ArrayList();
    int lineRead = 0;
    try{
        File file = new File("yourfile.txt");
        BufferedReader br = new BufferedReader(new FileReader(file)));
        String line;
        while ((line = br.readLine()) != null) {
           String[] data = line.split(":");
           if(data.length > 0){
               filmList.add(new String[]{data[1],data[3],data[5],data[7]});
           }
           lineRead++;
        }
    }catch(Exception ex){
        System.out.println("Error reading line "+lineRead);
        ex.printStackTrace(); //very ugly using this (common is logging it)
    }
    return filmList;
 }
Community
  • 1
  • 1
Solano
  • 550
  • 2
  • 9
  • 1
    in this code I get this : " Type mismatch: cannot convert from String[] to ArrayList" , but by changing films to String [] results in more errors – Unknown Jun 05 '15 at 11:57
  • Which line is that? some mistake i cant find yet – Solano Jun 05 '15 at 12:00
  • I did some modifications on the code above..try again copy and paste please – Solano Jun 05 '15 at 12:01
  • 1
    after using dokimi3run ( a class I created with teh sole purpose of creating an object of the class with your code so that I wouldn't have to deal with making the methods static ) I got these errors : Error reading line 0 java.lang.ArrayIndexOutOfBoundsException: 4 at ergasia.Dokimi3.getFilms(Dokimi3.java:44) at ergasia.Dokimi3.existsFilm(Dokimi3.java:25) at ergasia.dokimi3run.main(dokimi3run.java:11) Error reading line 0 java.lang.ArrayIndexOutOfBoundsException: 4 at ergasia.Dokimi3.getFilms(Dokimi3.java:44) at ergasia.dokimi3run.main(dokimi3run.java:12) – Unknown Jun 05 '15 at 12:11
  • Did you add the ":" extra symbols at your line? because it expects that you have 8 positions after split(":")... add ":" for id : 1 : title : x : category : action etc... add ":" for all divisions – Solano Jun 05 '15 at 12:18
  • I think i know what you did.... your film result only have 4 positions: ID TITLE CATEGORY DESCRIPTION, so you are trying to access position 4 from film (film[4]) it doesnt exists... it only exist film[0] film[1] film[2] and film[3]. – Solano Jun 05 '15 at 12:30
  • after creating a new file which I changed a couple of times to match with what you said and testing it although it didn't show any errors this time I didn't seem to work properly though... what I mean is that I added some println to check the results and they didn't even appear for some reason. Still, this is the closest I have been to doing it to be honest. – Unknown Jun 05 '15 at 12:33
  • it doesnt print anything with systemout ? – Solano Jun 05 '15 at 12:36
  • I added systemouts to check the flow since in the first run I encountered zero errors but even though I addes system outs to all the methods during their flow as a kind of flag to see if all is good none of the systemouts showed up but I am still looking to see if I messed up the placing since considering all things it is not unlikely. – Unknown Jun 05 '15 at 12:41
  • could you please upvote and accept my answer ? thank you also – Solano Jun 05 '15 at 13:19
  • 1
    I tried to but it said I don't have enough reputation – Unknown Jun 05 '15 at 13:30