2014-05-02 142 views
1

如何提取从文本文件中的数据在Java中

 
while (myFile.hasNextLine()) {

if(myFile.next().equals("Oval")) { System.out.println("this is an Oval"); } else if(myFile.next().equals("Rectangle")) { System.out.println("this is an Rectangle"); }

的文件包含以下
椭圆形10 10 80 90红
椭圆形20 20 50 60蓝
矩形10 10 100 100绿色

我想提取数据并根据行开头指明的类型将它们传递给特定的构造函数。

,但我得到这个奇怪的输出

这是一个椭圆形 异常线程“main” java.util.NoSuchElementException 这是一个矩形 在java.util.Scanner.throwFor(扫描仪。 java:907) 这是一个Rectangle 位于Test.Main.main上的java.util.Scanner.next(Scanner.java:1416) (sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main( AppMain.java:134)

过程完成,退出代码为1

回答

1

您需要将next()hasNext()方法调用匹配,以配合个别字符串令牌

while (myFile.hasNext()) { 
    String token = myFile.next(); 

    if (token.equals("Oval")) { 
     System.out.println("this is an Oval"); 
    } 
    ... 
} 
4

明白,当你扫描仪对象调用next(),它吃的下一个标记,然后返回给你。如果您不将字符串赋值返回给变量,它将永远丢失,并且下一次您拨打next()时,您将获得一个新的令牌。获取令牌更好,把它分配给一个String变量,然后做你的if测试。不要在if布尔测试块中调用next()

即是这样的:

while (myFile.hasNextLine()) { 

    // get the token **once** and assign it to a local variable 
    String text = myFile.nextLine(); 

    // now use the local variable to your heart's content  
    if(text.equals("Oval")) { 
     System.out.println("this is an Oval"); 

    } 

    else if(text.equals("Rectangle")) { 
     System.out.println("this is an Rectangle"); 

    } 

另外,如果你测试hasNextLine(),那么你应该叫nextLine(),不next(),你应该把它仅一次每个hasNextLine。


当从文本文件中提取数据行时,我有时会使用多个扫描仪。例如:

Scanner fileScanner = new Scanner(myFile); 
while (fileScanner.hasNextLine()) { 
    Scanner lineScanner = new Scanner(fileScanner.nextLine()); 

    // use the lineScanner to extract tokens from the line 

    lineScanner.close(); 
} 
fileScanner.close(); // likely done in a finally block after null check 
+0

要么调用'下一个()'和nextLine()后''扔掉该行,因为OP只检查“椭圆形”和“矩形”或拆分字符串并采取第一部分。 –

+0

非常感谢我不知道这一点,还有一个想法是如何摆脱'NoSuchElementException',不应该使用'hasNextLine()'来遍历文件? – RootOfMinusOne

+0

@RootOfMinusOne:只要它能正常工作并遵守文件结构,您可以通过任何方式遍历文件。我经常使用基于文件的扫描器通过'hasNextLine()'''nextLine()'获取每一行,然后使用单独的基于字符串的扫描器来提取行中的单个标记。但是如果你走这条路线,一定要处理每个基于字符串的扫描仪。 –

相关问题