karthik gorijavolu
karthik gorijavolu

Reputation: 860

Java Scanner is not working while reading a file

public class Test {

    static private Scanner x;

    public static void main(String args[])
    {
        try {
            x=new Scanner(new File("C:\\Users\\scoda\\workspace\\Nikhil\\src\\chinese.txt"));
            x.useDelimiter(" ");
            while(x.hasNext())  
            {

                String a=x.next();
                String b=x.next();              
                String c=x.next();
                System.out.println(a+b+c);

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

My input file is

12 karthik kk
23 gg gg

Expected output:

12karthikkk
23gggg

Actual output:

12karthikkk
23
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)

I am trying to debug the issue from a long time . Help is appreciated.

Upvotes: 0

Views: 443

Answers (2)

prasanna sudharsan
prasanna sudharsan

Reputation: 1

Try this

  StringBuffer buffer = new StringBuffer(10);
        try
        {
            x = new Scanner(new File("D:\\test1.txt"));
            x.useDelimiter(" ");

            while (x.hasNext())
            {

                String a = x.next();
                buffer.append(a);

            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(buffer.toString());
    }

Upvotes: 0

shmosel
shmosel

Reputation: 50776

Because you changed the delimiter to space, the newline isn't counted as a separator, and there are actually only 5 tokens in your string:

  1. 12
  2. karthik
  3. kk

    23

  4. gg
  5. gg

Your code is throwing an exception on the second call to String c=x.next();, because there is no sixth token. If you remove the x.useDelimiter(" "); statement, it will use the default whitespace delimiter, which will split on your newline as well, resulting in 6 tokens.

Upvotes: 4

Related Questions