nextInt () after the third integer

3

Given the example.csv:

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

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

My question: How to ignore, for example, the first three values and pick up only the last two ?? Do I still use .nextInt() or is there another method to help me with this?

    
asked by anonymous 06.11.2018 / 17:20

2 answers

6

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

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

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

See working at ideone

    
06.11.2018 / 17:31
2

You can use .skip () by passing a regular expression to ignore the unwanted parts. See the 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 whatever comes before the nth semicolon. If you run the example above the output will be only what you have after the 3rd integer:

Value: 43

Value: 54

    
07.11.2018 / 20:30