简体   繁体   English

读取文件时Java扫描仪不起作用

[英]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. 感谢帮助。

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: 因为您将分隔符更改为空格,所以换行符不算作分隔符,并且字符串中实际上只有5个标记:

  1. 12 12
  2. karthik KARTHIK
  3. kk KK

    23 23

  4. gg GG
  5. gg GG

Your code is throwing an exception on the second call to String c=x.next(); 您的代码在第二次调用String c=x.next();引发异常String c=x.next(); , because there is no sixth token. ,因为没有第六个令牌。 If you remove the x.useDelimiter(" "); 如果删除x.useDelimiter(" "); statement, it will use the default whitespace delimiter , which will split on your newline as well, resulting in 6 tokens. 语句,它将使用默认的空格分隔符 ,它也会在换行符上拆分,从而产生6个标记。

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());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM