Skip to main content
GameDev.net gamedev.net
🔒 Locked

Java Scanner problem

Started by arroyjose Mar 11, 2008 at 10:45 PM 0 replies 950+ views
Original Post
arroyjose
arroyjose
I'm a little rusty on Java because I haven't used it in a few months. And I'm having a problem with Scanner objects. If I create multiple Scanner objects initialized to the same InputStream will that cause both scanners to behave as if they were the same? The constructor signature from the documentation is: Scanner(InputStream source) Constructs a new Scanner that produces values scanned from the specified input stream. I have an InputStream object that I want to count how many lines it has so I can create an array. For this I use a Scanner object. Then once I know how many lines there are I read the file again to get the data.

public static boolean connected(InputStream network)
{
	String aLine = null;
		
	Scanner fileIn = new Scanner(network);
	Scanner readData = new Scanner(network);
		
	// Determine the number of elements in the file
	int size = 0;
		
	// The entire file is read first to determine the number of elements
	// This avoids having to construct an array of a very big size and thus wasting space
	while(fileIn.hasNextLine())
	{
		System.out.println(fileIn.nextLine());
		size += 1;
	}
		
	System.out.println(size);
	// Everything good up to this point.
	
	
	while(readData.hasNextLine())
	{
		// Here it doesn't read anything

		aLine = readData.nextLine();
	}
		
	return false;
}

Maybe the problem is that I'm treating the InputStream object as a file. Is that the right way to think about it?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.