Hello guys, I've been trying to make a program that takes the IDs from a file and make them into a 1D array.

The input file looks like this :
201053420
201052456
201488540
201384345

And it should be working even if there's more than 4 IDs.

import java.util.*;
import java.io.*;
public class Assign6 {

    public static void main(String[] args) throws FileNotFoundException {
    	Scanner stuID = new Scanner(new File("ICS102.txt"));
    	int numOfID = 0;
    	while (stuID.hasNextInt()) {
                numOfID++;
         }
        System.out.println(numOfID);

        int [] IDs = new int [numOfID];
    	for (int i = 0; i < numOfID; i++ ) {
    		IDs[i] = stuID.nextInt();
    	}
    	for (int i = 0; i<numOfID; i++)
    		System.out.println(IDs[i]);



    }


}

Apparently there's a problem in the first while loop, I don't know why. If someone can help me with and explain, I'd be thankful.

Recommended Answers

All 3 Replies

Can you explain what the problem is. Show the output and explain what it should be.
Do you get errors? If so, please copy the full text and paste it here.

Yes. The problem is that I can't get a number out of the first loop while. I need the "numOfID" to be an integer number to know the size of an array.

while (stuID.hasNextInt()) {
                numOfID++;
         }

this is the problem actually, but I don't know how to make it right.

The doc for the hasNext() method says: This method may block while waiting for input to scan. I assume that this is what is happening to you.
The Scanner class is waiting for some more input.
Try using a different has... method or
Try using a class or combination of classes that recognizes EOF and returns a null when there is no more data left to be read.

Do a Search here for sample code that uses BufferedReader class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.