开发者

When using a scanner on a series of integers, how do I skip some integers?

The following code for example

while (lineScan.hasNextLine()) {
   int x = lineScan.nextInt();
   x = lineScan.nextInt();
   x = lineScan.nextInt();
   x = lineScan.nextInt();
   x = lineScan.nextInt();
   System.out.println(x +开发者_StackOverflow社区 "\n");
}

will print out every fifth integer.

Is there an easy way to skip over every fifth integer?


while (lineScan.hasNextLine()) {
    for(int i=0; i<5; i++)
        x = lineScan.nextInt();

    System.out.println(x + "\n");
}

OR

while (lineScan.hasNextLine()) {
    for(int i=0; i<4; i++) 
        lineScan.nextInt();

    x = lineScan.nextInt();
    System.out.println(x + "\n");
}

Seems rather primitive, but, it works.


I see lot's of folks checking the hasNextLine and then reading ints. I've always been taught that if you check hasNextX you should follow this with a call to nextX, if the check passes, but never nextY. In other words, if you check hasNextLine(), you should read in nextLine(), and if you want int, you should check hasNextInt() before reading in nextInt() with one check for every read. In your situation, I'd read in the line and then manipulate it either with another Scanner object that works on just that line (don't forget to close it when done to save on resources!) or use String split.

For example if doing it the first way, I'd do something like:

  while (lineScan.hasNextLine()) {
     String line = lineScan.nextLine();

     Scanner innerScanner = new Scanner(line);
     int x = 0;
     while (innerScanner.hasNextInt()) {
        x = innerScanner.nextInt();
     }
     System.out.println("" + x);
     innerScanner.close();
  }

and for the second way:

  while (lineScan.hasNextLine()) {
     String line = lineScan.nextLine();

     String[] splitLine = line.split(" "); // the delimiter may be different! a comma?
     if (splitLine.length >= 5) {
        System.out.println(splitLine[4]);
     }
  }


This will do:

int i = 0;
while(lineScan.hasNextLine()) {
   i++;
   int x = lineScan.nextInt();
   if (x%5 == 0) System.out.println(x + "\n");
}


Just do nextInt() and ignore the result?


Use a loop, I suppose:

while(lineScan.hasNextLine()) {
     for(int i = 0; i < 4; i++) lineScan.nextInt();
     System.out.println(Integer.toString(lineScan.nextInt()) + "\n"); // is this supposed to be "popularity"?
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜