• 0

[JAVA] Scanner help


Question

I am trying to get java to scan a text file and pull out numbers only ignoring the text. The file looks like this:

100 100 Start of rectangle

200 100

200 200

100 200

100 100 End of rectangle

-1 -1

300 300 Start of triangle

350 200

400 300

300 300 End of triangle

-1 -1

Here is my code some stuff is not needed but i am not finished writing it to do other things:

import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

public class PolygonPanel extends JPanel 
{
	public PolygonPanel() throws IOException
	{
		int numX, numY, n;

		n = 0;

		Scanner fileScan = new Scanner (new File("a.dat"));

		while (fileScan.hasNext())
		{
			numX = fileScan.nextInt();
			numY = fileScan.nextInt();

			if (numX == -1 && numY == -1)
			{				
				n++;
			}			
		}

		System.out.print("" + n);

		setBackground (Color.white);
		setPreferredSize (new Dimension(1000, 1000));
	}
}

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I wouldn't use Scanner, I would use the BufferedReader, read every line as a String (using readLine()), then put it in a StringTokenizer. Then you just call nextToken() twice and you get the first 2 tokens on each line, and you bypass the 3rd token completely.

Link to comment
Share on other sites

  • 0

I wouldn't use Scanner, I would use the BufferedReader, read every line as a String (using readLine()), then put it in a StringTokenizer. Then you just call nextToken() twice and you get the first 2 tokens on each line, and you bypass the 3rd token completely.

This is a very good approach, you can still use scanner as it has a line reader as well.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.