Search code examples
javalinked-listbufferedreaderstringtokenizerparseint

How can i pass all integers i this loop and stop before the last line


this is my input

first line
5 6
3 4
2 3
2 5
1 0
word 2 2 4

i need to add all the integers to a graph but not the last line (word 1 2 4)..

i have splitted the first line (first line etc.) and put them in a arraylist.. No problem there

but then i have this for-loop

for (int i = 0; i < (amount of lines); i++) {
        StringTokenizer st = new StringTokenizer(in.readLine());
        graph.addEdge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
    }

i cant write in the code how many times i want it to put integers, because my code should run generally with other inputs... How can i make it stop before the last line, i still need to be able to use the last bufferreaderline


Solution

  • I would just use try-catch:

        ArrayList<Integer> nums = new ArrayList<Integer>();
        String lastLine = "";
    
        try {
            while ((lastLine = in.readLine()) != null) {
    
                StringTokenizer st2 = new StringTokenizer(lastLine);
                graph.addEdge(Integer.parseInt(st2.nextToken()), 
                              Integer.parseInt(st2.nextToken()));
            }
        }
        catch (NumberFormatException e) {}
    
        System.out.println(lastLine);