2017-04-10 110 views
-3

我曾经见过类似的话题,但似乎无法将一个工作解决方案拼凑在一起。我正在编写一个程序(部分)从stdin读取值以执行一些操作。但是,我想在运行时重定向文本文件中的输入,所以我不能只使用Ctrl + Z(窗口)发出EOF。Java扫描仪hasNextLine()阻止问题

String s; 
    int v2 = 0; 
    double w = 0; 
    int v1 = 0; 
    int i = 0; 
    Scanner sc = new Scanner(System.in); 
    while(sc.hasNextLine()){ 
     s = sc.nextLine(); 
     String[] arr = s.trim().split("\\s+"); 

     v1 = Integer.parseInt(arr[0]); 
     v2 = Integer.parseInt(arr[1]); 
     w = Double.parseDouble(arr[2]); 

     i++; 
    } 
    System.out.println(i); 
    sc.close(); 

我似乎从来没有到最后的打印语句,(我的猜测反正)似乎hasNextLine()被无限期封锁。

下面是输入文件的格式的例子:

0 1 5.0 
1 2 5.0 
2 3 5.0 
3 4 5.0 
4 5 5.0 
12 13 5.0 
13 14 5.0 
14 15 5.0 
... 
-1 

它始终是在INT INT双的格式,但之间的间距可以变化,因此字符串操作。它也总是以-1结束。

我已经尝试了以下无济于事

String s; 
int v2 = 0; 
double w = 0; 
int v1 = 0; 
int i = 0; 
Scanner sc = new Scanner(System.in); 
while(sc.hasNextLine()){ 
    s = sc.nextLine(); 
    String[] arr = s.trim().split("\\s+"); 

    v1 = Integer.parseInt(arr[0]); 
    if(v1 < 0){ 
     break; 
    } 
    v2 = Integer.parseInt(arr[1]); 
    w = Double.parseDouble(arr[2]); 

    i++; 
} 
System.out.println(i); 
sc.close(); 

我漏掉了最不相关,以避免混乱的代码。如果需要,我可以发布。

感谢您的关注。

编辑:为清晰起见编辑。还注意到,它挂在输入文件的最后一行,而不管行内容(即有效行挂起)。我通过日食(霓虹灯)重定向。

+0

的可能的复制[如何摆脱while循环与扫描仪的方法“hasNext”为条件的Java?(http://stackoverflow.com/questions/10490344/how-to-get-out- java-with-scanner-method-hasnext-as-condition) – Tom

+0

我很抱歉,我用另一个版本的代码试图绕过hasNextLine()。我还看到了您提到的线索,并试图实施该解决方案,但无效,导致我怀疑问题可能会有所不同。 –

+0

*“如何试图实现该解决方案”*看起来像? – Tom

回答

0

你的代码似乎运作良好。虽然你可以检查hasNextLine以及如果EOF被自定义检查其他条件(如在你的情况下有-1)。如果你的代码容易出错,你也可以捕获一些异常。下面的代码适合我。

 Scanner scanner = new Scanner(new File("/opt/test.txt")); 
     int secondValue = 0; 
     double lastValue = 0; 
     int firstValue = 0; 
     int LineNumber = 0; 
     while ((scanner.hasNextLine())) { 
      try { 

       String[] arr = scanner.nextLine().trim().split("\\s+"); 

       firstValue = Integer.parseInt(arr[0]); 
       secondValue = Integer.parseInt(arr[1]); 
       lastValue = Double.parseDouble(arr[2]); 
       doSomeThing(firstValue,secondValue,lastValue); 

       LineNumber++; 
      } catch (Exception excep) { 

      } 
     } 
     System.out.println(LineNumber); 
} 
+0

感谢您的测试。我敢打赌,这是它在日食中的怪癖(或者在我的系统中有一些奇怪的设置)。 –

+0

删除我的评论,由于汤姆的错字.. –

+1

哦,只是注意到我的两个下线...谢谢汤姆 –