Hi guys, I have a problem.

Im trying to read from a file which contains

one, two, three, four.

The output I get is
one
two
three
four

But I want to make it read every other line.
one
three
etc.

How would I go about that?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileSkipLine
{
 public static void main( String strarrArgs[] )
 {
  File   myFile;
  Scanner myScanner;
  boolean bContinue;
  String  strLine;
  try
  {

   myFile = new File( "C:\\temp\\data.txt" );

   myScanner = new Scanner( myFile );
   
   bContinue = myScanner.hasNext( );
   while( bContinue == true ) 
   {

    strLine   = myScanner.nextLine( );
    
    System.out.println( strLine );
    
    bContinue = myScanner.hasNext( );
   }
  }
  catch( FileNotFoundException exp )
  {
   System.out.println( " didn't find the file, does it exist? is the location correct? ");
  }
  catch( Exception exp )
  {
   System.out.println( " an exception happened, here is the message " + exp.getMessage( ) );
   
   exp.printStackTrace( ); 
  } }  }

Read every line but ignore every other one - ie read/read/print/read/read/print etc

Read every line but ignore every other one - ie read/read/print/read/read/print etc

okay so this is what i did inside the while loop

while( bContinue == true ) 
   {

    strLine   = myScanner.nextLine( );
    strLine   = myScanner.nextLine( );
    
    System.out.println( strLine );
    
    bContinue = myScanner.hasNext( );
   }

it gives me the second line and fourth line etc and an error.

:-/

... so, the game is to guess what error you got?

My guess is "NoSuchElementException".

If my guess wins, try

int count = 0;
while (myScanner.hasNextLine()) {
    strLine = myScanner.nextLine();
    count++;
    if (count % 2 == 1) {
        System.out.println(strLine);
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.