+ 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); } }
9 Réponses
+ 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);
}
}
+ 3
Denise Roßberg thank you so much
+ 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.
+ 2
Asker Your welcome. :)
+ 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)
+ 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 :/
+ 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.
+ 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.
+ 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.