CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2009
    Posts
    5

    Unhappy getting *.hasNext() return false in scanner class

    I'm having a hard time getting a loop to work for me. I'm writing a program which parses strings, first trying to read from a text file from command line argument, and if that doesn't work, then parse input from the user. The problem I'm having is copying the text to an Arraylist using the hasNext() method. When using the text file everything works fine, but when I use a scanner(System.in), it blocks waiting for me to input more text forever. Can anybody tell me an easy way to get hasNext to return false under these conditions? Another scanner type maybe? Any help would be greatly appreciated. The example is below.

    try {
    File inputFile = new File(args[0]);
    dataScanner = new Scanner(inputFile);
    }
    catch (IOException e) {
    System.out.println("IO exception thrown");
    System.out.println("Data must be input manually");
    dataScanner = new Scanner(System.in);
    }
    catch (ArrayIndexOutOfBoundsException e){
    System.out.println("No input found, Data must be input manually");
    dataScanner = new Scanner(System.in);
    }

    ArrayList<String> stringData = new ArrayList<String>();

    int line = 0;
    **********************************************************************
    while (dataScanner.hasNext()) {

    stringData.add(line, dataScanner.next());
    System.out.println(stringData.get(line));
    line++;

    }
    **********************************************************************

    System.out.println("Loop finished!");
    //dataScanner.close();

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: getting *.hasNext() return false in scanner class

    When scanning a file eventually the scanner gets to the end of stream marker and so it knows there's no more data to scan and so hasNext() returns false. However, when scanning from the command line there is no end of stream marker so hasNext() bocks waiting for the next chunk of data (or the end of stream marker).

    You need to decide how you are going to end command line input, eg is it on entering a single line, on entering multiples lines of text followed by a blank line or on entering multiples lines of text followed a specific keystroke/keyword eg END, EOF, STOP etc. You then need to add code to your while loop to find the end of input marker and exit the loop.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured