0

The Error is not in the while condition

I load a file (the file contains three columns of numbers separated by tab) and I get this error :

java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Unknown Source)at java.util.Scanner.next(Unknown Source)at webscience.Main.countTimesListened(Main.java:43)at webscience.Main.main(Main.java:21)

System.out.println ("Program Starts");

    File timesListened = Loader.loadFile();
    countTimesListened(timesListened);

}

public static void countTimesListened (File file) throws FileNotFoundException
{
    Scanner sc;

    UserList userList = new UserList();
    TimesListened timesListened = new TimesListened();

    try
    {
        sc = new Scanner (file);
        sc.useDelimiter("\\t");

        while (sc.hasNextLine() && sc.nextLine() != "")
        {
            sc.reset();

            String userID = sc.next();
            String artistID = sc.next();
            String weight = sc.next();

            userID = userID.replaceAll("\\t", "");
            artistID = artistID.replaceAll("\\t", "");
            weight = weight.replaceAll("\\t", "");

            User user = new User (userID);
            Artist artist = new Artist (artistID);
            user.listensTo(artist, weight);

            if (!userList.userExists(user))
                userList.addUser(user);


            int num = Integer.parseInt(weight);

            if (!timesListened.artistExists(artistID))
                timesListened.addArtistWeight(artistID, num);
            else
                timesListened.increaseArtistWeight(artistID, num);
            System.out.print(userID + artistID + weight);

        }
        sc.close();
    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (NoSuchElementException e)
    {
        e.printStackTrace();
    }

    File outputFile = new File ("user_artists.txt");
    FileOutputStream fos = new FileOutputStream(outputFile);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.out.println(timesListened.toString());
user3469716
  • 25
  • 1
  • 6
  • `sc.nextLine() != ""` -> [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo Mar 19 '15 at 18:42
  • This isn't the source of the error. What I wrote works good but the error is elsewhere – user3469716 Mar 19 '15 at 18:47
  • When I change it to equals the code does not run at all – user3469716 Mar 19 '15 at 19:00
  • `sc.nextLine() != ""` shouldn't be replaced with `sc.nextLine().equals("")` but `!sc.nextLine().equals("")` - you negate result of `equals`. – Pshemo Mar 19 '15 at 19:11
  • Anyway it is hard to give you precise answer without seeing what input you are trying to read/parse. – Pshemo Mar 19 '15 at 19:12

0 Answers0