reading file StringTokenizer to int

3.8k Views Asked by At

I have create the following program and I am little stuck here. Here is the code:

class ProductNameQuan{
    public static void main(String[] args)
    {
        String fileName = "stockhouse.txt";
        StringTokenizer line;
        String ProdName;
        String quantity;
        try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            line = in.readLine();
            while (line != null) {
                 ProdName = line.nextToken();
                 quantity = line.nextToken();
                 System.out.println(line);
                 line = in.readLine();
            }
       in.close();
       } catch (IOException iox)
       {
           System.out.println("Problem reading " + fileName);
       }
    }
}

I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer. Now the other problem is that I need the quantity to be an integer instead of string.

The file includes something like that: Ball 32 tennis 322 fireball 54 .. . . . . Any ideas?

1

There are 1 best solutions below

2
On

I would place this in a helper function, maybe called parseString

class ProductNameQuan {
    public static void main(String[] args)
    {
        ...
        try {
            BufferedReader in = ...
            line = in.readLine();
            while (line != null) {
                ProductNameQuan.parseString(line);
            }
        }
        ...
    }

    public static void parseString(String someString) 
    {
        StringTokenizer st = new StringTokenizer(someString);
        while (st.hasMoreTokens()) {
            String token = line.nextToken();
            try {
                int quantity = Integer.parseInt(token)
                // process number
            } catch(NumberFormatException ex) {
                // process string token
        }
    }

}