javaregexjava.util.scanner

Using scanner to get integers and a string from a file


I have a file with contents

v1 0 2 v2 0 3 v3 1 2 v4 1 2 v5 1 3

I need to be able to get the information and store this in three different variables (a String and 2 ints). I am having trouble getting my head around the pattern I would use with the useDelimiter function.

Also is there a way that I don't have to first split it into separate strings, then parseInt from that string? So I have a class called Task which has a String and two Ints. I need to be able to go through the file and create multiple tasks e.g. Task(v1,0,2), Task(v2,0,3).

Thanks.


Solution

  • I think you're over-thinking things -- you don't need to use useDelimiter since Java's Scanner object automatically will split via whitespace.

    Scanner scan = new Scanner(new File("myFile"));
    
    ArrayList<Task> output = new ArrayList<Task>();
    
    while (scan.hasNext()) {
        String s = scan.next();
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();
        output.add(new Task(s, num1, num2));
    }
    

    Note that the above code will fail if the input does not exactly match the pattern of string-int-int -- the nextInt method in a Scanner will fail if the next token cannot be interpreted as an int, and the code will throw an exception if the number of tokens in the input is not a multiple of three.