M4nB3arP1g Posted January 25, 2010 Share Posted January 25, 2010 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 More sharing options...
0 fo7557 Posted January 25, 2010 Share Posted January 25, 2010 what's your question? Link to comment Share on other sites More sharing options...
0 shiny_red_cobra Posted January 25, 2010 Share Posted January 25, 2010 (edited) 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 More sharing options...
0 Argote Posted January 26, 2010 Share Posted January 26, 2010 (edited) 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 More sharing options...
Question
M4nB3arP1g
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