Error while redirecting the input from file

一笑奈何 提交于 2019-12-06 11:16:50

Don't create a Scanner object in every method. Pass the first Scanner object you have created around.

Here is a list of changes that should fix the issue:

--- demo-old.java   2012-01-25 23:12:54.000000000 +0530
+++ demo.java   2012-01-25 23:13:45.000000000 +0530
@@ -10,4 +10,3 @@

-void read_graph() {
-    Scanner sc = new Scanner(System.in);
+void read_graph(Scanner sc) {
     N = sc.nextInt();
@@ -26,4 +25,3 @@

-void query(){
-Scanner sc = new Scanner(System.in);
+void query(Scanner sc){
     int P, Q;
@@ -53,4 +51,4 @@
     while (numGraphs>0){
-        G.read_graph();
-        G.query();
+        G.read_graph(sc);
+        G.query(sc);
         numGraphs--;

Why are you creating 3 scanners? It is possible that it is choking in the lines

1) P = sc.nextInt();
2) Q = sc.nextInt();

because the input with only 1 int is being read in line 1 and then line 2 is trying to scan the nextInt() for an empty line.

I have no idea why this would work when inputing by hand, unless the input is in a different order.

You should not use < to redirect input. You need to use scanner class to read from file.

File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
//logic
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!