+ 1

the program still running without any output..why ? (the code is below)

import java.io.File; import java.util.Scanner; class p { public static void main (String [] args ) throws Exception { File f= new File("d:\\1.txt"); Scanner s = new Scanner (f); int a=0; while (s.hasNextLine()){ a+=1; } s.close(); System.out.println (a); } }

26th Jan 2019, 1:26 PM
De Vinci
9 Respuestas
+ 2
Look here: https://stackoverflow.com/questions/8352040/scanner-on-text-file-hasnext-is-infinite/8352102 Edit: I checked it in my own IDE and it works. import java.io.File; import java.util.Scanner; class p { public static void main (String [] args ) throws Exception { File f= new File("d:\\1.txt"); Scanner s = new Scanner (f); int a=0; while (s.hasNextLine()){ a++; //(same as a+=1) s.nextLine (); } s.close(); System.out.println (a); } }
26th Jan 2019, 7:19 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Denise Roßberg thank you so much
26th Jan 2019, 7:40 PM
De Vinci
+ 2
https://www.sololearn.com/learn/Java/2187/?ref=app You can try this examples. Maybe you find the error by checking rhe differences between your program and the examples.
26th Jan 2019, 4:26 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Asker Your welcome. :)
26th Jan 2019, 7:44 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I'm not sure if you can use the Scanner. Here you find some examples how to read a file. https://www.tutorialspoint.com/java/java_files_io.htm And which output to you get? "No output" or an error message or 0 (because a = 0)
26th Jan 2019, 3:32 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Denise Roßberg i don't get anything, the program keep running till i stop it..i guess the code is correct and should works :/
26th Jan 2019, 3:45 PM
De Vinci
+ 1
Maybe the while loop is running infinity. And the error has to do with the condition s.hasNextLine (); int a = 0 while-loop print a You have to get at least 0. And if you got nothing your program is maybe still running.
26th Jan 2019, 4:13 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Denise Roßberg yes i have seen already this example..but it gives just word by word..i'm looking for the whole line. The goal of my program is to return the number of lines in my file.
26th Jan 2019, 5:15 PM
De Vinci
+ 1
I found the failure. Your loop is running infinity. while (s.hasNextLine ()){ //returns true //but hasNextLine () don't move to the next line //call nextLine () to move to the next line s.nextLine (); } Hope this helps.
26th Jan 2019, 7:16 PM
Denise Roßberg
Denise Roßberg - avatar