Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Apr 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Reading txt file contents into parallel arrays code not working


    // Create File Object
    String fileName = "myfile.txt";
    File file = new File(fileName);

    if (file.exists())
    {

    Scanner scan = new Scanner(file);
    int counter = 0;

    while(scan.hasNext())
    {


    String code = scan.next();
    String moduleName = scan.next();
    int totalPurchase = scan.nextInt();

    moduleCodes[counter] = code;
    moduleNames[counter] = moduleName;
    numberOfStudents[counter] = totalPurchase;

    counter++;


    }

    }


    The above code doesn't work.

    When I try to print the first element of the first array like this:
    System.out.println(moduleCodes[0]);
    it doesn't work, it just prints out Null.

    Note: The code above for reading the file contents into arrays in inside a method.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,980
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Put an else clause on the if (file.exists()). Although the scanner is a checked exception when given a file, it won't ever trigger if you use a file.exists() check prior to creating the scanner. Everything else looks correct.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •