-2

I keep on getting a NumberFormatException in my code, but I can't seem to figure out why.

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

public class SongCollection
{
    ArrayList<Song> songs;
    public SongCollection(ArrayList<Song> songs) {
        this.songs = songs;
    }    

    public void addSong(String line) {
        String[] parts = line.split("\t");
        int year = Integer.parseInt(parts[0]);
        int rank = Integer.parseInt(parts[1]);
        String artist = parts[2];
        String title = parts[3];
        Song addedSong = new Song(year, rank, artist, title);
        songs.add(addedSong);
    }

    public void printSongs(PrintStream output) {
        for (int i = 0; i < songs.size(); i++) {
            Song song = songs.get(i);
            output.println(song.toString());
        }
    }
}

The string I used for the addSong method was from this input file:

The error I get is "java.lang.NumberFormatException: For input string "1965" (in java.lang.NumberFormatException)"

EDIT (adding debugger window picture): enter image description here

Thank you for your help!

Wajih
  • 4,227
  • 2
  • 25
  • 40
ljjel
  • 1
  • 3

2 Answers2

-1
your input "1965" doesn't contain "\t". so the value of line will be 1965, 
 int year = Integer.parseInt(parts[0]); 
parts[0] will have 1965 value, and it will be complied successfully, but
 int rank = Integer.parseInt(parts[1]);

part[1] will not have any thing so the NumberFormatException will occur, make sure your input should contain '\t' character and numbers so that the values of parts[0] and parts[1] should be numbers.

Imtiaz Ali
  • 302
  • 1
  • 3
  • 8
  • The error occurs on the int year line, so doesn't that mean that the NumberFormatException is occurring on that line too? – ljjel Mar 26 '17 at 06:47
-1

I see why I kept on getting an error. I needed to remove the BOM from the file since I was using Notepad to open it. Everything works now, thanks for all the help!

ljjel
  • 1
  • 3