Search code examples
javastringjava.util.scanner

Scanner.next() doesn't read the first character in every second line


The following inputs are supplied to this piece of code:

5
0 4 15
1 0 14 2 7 3 23
2 0 7
3 1 23 4 16
4 2 15 3 9

The problem is that whenever the line number is odd, the first integer will not be read by "String newVertexID = inputs.next("\\d+");" as intended but rather by "System.out.println("next: " + inputs.next("\\d+"))", i.e. 0, 2, 4 are being assigned to the newVertexID, as intended, but 1, 3 are being passed to the second print statement, which is not what I want.

I initially thought that it's because of the newline character at the end of each line that's causing the issue, but I've tried so many things (everything I've commented out is what I've tried) that I've now begun to doubt it. How can I figure out why?

 Graph graph = new Graph();  
        Scanner inputs = new Scanner(System.in);
        int vertexCounts = inputs.nextInt();
        // inputs.nextLine();
        for (int i = 0; i < vertexCounts; i++){
            // inputs.nextLine();
            inputs.skip("\n");
            String newVertexID = inputs.next("\\d+");
            System.out.println(newVertexID);
            Vertex newVertex = new Vertex(newVertexID);
            graph.addVertex(newVertex);
            while(inputs.hasNextInt()){
                System.out.println("Why are you running");
                System.out.println("next: " + inputs.next("\\d+"));
                System.out.println(inputs.nextInt());
                // graph.addEdge(newVertexID, inputs.next(), inputs.nextInt());
            }
            // inputs.nextLine();

        }

Solution

  • Try it like this. This is one of the few times it can be useful to use two scanners, one to read the line, the other to parse it. I added a few output enhancements.

    Scanner inputs = new Scanner(System.in);
    int vertexCounts = inputs.nextInt();
    inputs.nextLine();  // remove extra nl in input buffer.
    System.out.println(vertexCounts);
    for (int i = 0; i < vertexCounts; i++){
        String line = inputs.nextLine();
        System.out.println(line);
        Scanner parseLine = new Scanner(line);
        int vertexID = parseLine.nextInt();
        System.out.println("vertexID = " + vertexID);
     
        while(parseLine.hasNextInt()){
            System.out.println("Why are you running");
            System.out.println("next: " + parseLine.nextInt());
            // graph.addEdge(newVertexID, inputs.next(), inputs.nextInt());
        }
    
    }