nextInt() after the third integer

Asked

Viewed 67 times

3

Given the example.csv:

nome;idade;10;21;32;43;54

I can use the class Scanner to read such a file. Using the method .useDelimiter() and taking advantage of the ; to pick up each value. So I use the .next() to the nome and to the idade. For the other five values use the .nextInt(), since they are all whole.

My question: How to ignore, for example, the first three values and take only the last two? I continue using the .nextInt() or there is another method that helps me in this?

  • could use next without being int, not to convert to numeric for no reason, and just not to use the value. (taking as string practically should not have overhead) - Anyway, the split resolves more directly, as mentioned by @Articuno (but will have to convert to numeric of qq way)

2 answers

6


Instead of using class methods Scanner for this, you can use split() in this string, after retrieving it from csv and taking only the final values, which will be the last two indices of the generated array:

String[] str = "nome;idade;10;21;32;43;54".split(";");

System.out.println(str[str.length-1] + " - " + str[str.length-2]);

See working on ideone

2

You can use . Skip() by passing a regular expression to ignore unwanted parts. See example below:

    public static void main(String[] args) {
    Scanner sc = new Scanner("nome;idade;10;21;32;43;54").useDelimiter(";").skip("((\\w*);){5}");

    while(sc.hasNext()) {
        System.out.println("Valor: " + sc.nextInt());
    }
}

The regular expression: ((\w*);){n} will ignore what comes before the nth semicolon. If you run the example above the output will be only what you have after the entire 3rd:

Value: 43

Value: 54

Browser other questions tagged

You are not signed in. Login or sign up in order to post.