-1

I just want to know what's the mistake here or what I shoul add or quit from my code.

I want to create an ArrayList from a scanner, but i can't. If I create an ArrayList without specifying the type it works. What's the prob? I've already got a class Song.

When I print my 1st try, the Array is full of "nulls". When I print the 2nd try, the Array is just as I need it. How can I do that my 1st try shows the same print as try 2?

Thanks!!

        ArrayList<Song> can = new ArrayList<Song>(); // 1st try
    ArrayList can1 = new ArrayList(); /2nd try

    Song song;
    Scanner scan = null;

    try {
        scan = new Scanner(new FileReader("src/arrayList/Song.dat"));

        while (scan.hasNext()) {
            can.add(Song(scan.next())); // 1st try
            can1.add(scan.next()); // 2nd try
        }    


    } catch (FileNotFoundException e) {
        System.err.println(e);
    } catch (InputMismatchException e) {
        System.err.println(e);
    } catch (java.util.NoSuchElementException e) {
        System.err.println(e);
    }
    finally {
        scan.close();
    }
  • You have to write `new Song(scan.next())` and you need a constructor in Song class like `public Song(String s){..` – nachokk Sep 22 '13 at 22:38

1 Answers1

2

The two approaches in creating the list are correct, but there are several difference in them. See the link in the bottom of the answer.

The problem is you're not instantiating properly the Song object, which is supposed to be added in the list. In order to do so, you have to use the new keyword. For example:

can.add(new Song(scan.next()));

Read more about:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147