#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Java ArrayList / File Input Help


    Hi, I'm writing a program for a Computer Science project and am having trouble. The program is dealing with creating a custom class (Height) with two private int variables (pounds, ounces). When working with the main file (HeightsSorter) I am trying to read a file for input, create Height objects from each line of input and add them to an existing ArrayList that I have created. I can't seem to figure this out. For some reason it doesn't seem to be adding any of my Height objects to my ArrayList. If anyone could help me it would be much appreciated!

    Here is the code I have for my main class:

    Scanner keyb = new Scanner(System.in);

    System.out.print("Enter the file name> ");

    String dataFile = keyb.next();

    Scanner readFile = new Scanner(new File(dataFile));

    int ft, in;

    ArrayList<Height> heights = new ArrayList<Height>();

    while (readFile.hasNextInt())
    {
    ft = readFile.nextInt();

    in = readFile.nextInt();

    heights.add(new Height(ft,in));
    }

    readFile.close();

    int i;

    System.out.println("Unsorted Names from "+dataFile+":");
    for (i=0; i<heights.size();i++)
    {
    System.out.println(heights.get(i));
    }



    The output is this:

    Enter the file name> heights.txt
    Unsorted Names from heights.txt:


    I am pretty sure that the file is right. I know that the name is. But I just don't know what I'm doing wrong!

    Please help,
    Addison
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    74
    Rep Power
    19
    Your code works perfectly here, after adding a try/catch around the File argument of the Scanner.

    I do advise you however to put the declaration of ft and in inside the while loop, as you now have the risk to end up with Height objects with the same attribute values.

    I also changed the last for-loop to:
    Code:
    for (i=0; i<heights.size();i++)
    {
        System.out.println(heights.get(i).toString());
    }
    and have the Height class override the toString method to for example:

    Code:
    public String toString()
    {
    	return "["+this.feet+","+this.inch+"]";
    
    }

IMN logo majestic logo threadwatch logo seochat tools logo