I tried to read lines of input until you reach EOF, then number and print all lines of content.
Sample Input
Hello world
I am a file
Read me until end-of-file.
Sample Output
1 Hello world
2 I am a file
3 Read me until end-of-file.
my code:
Scanner sc= new Scanner(System.in);
String msg= sc.next();
byte n=1;
n= sc.nextByte();
while(true){
System.out.println(n+" “+sc.hasNext(”/0"));
n++;
}
im getting error…can anyone help me with this
A few things I notice:
- Your loop never terminates - you have
true
for the while condition so that will never be false
and you have no break
statement.
- You are only calling
hasNext
without ever calling any of the next
methods. As long as it has something, it will just keep returning true forever.
- You say you are trying to read a file, but you passed
System.in
to the Scanner
so it will read the standard input at the command prompt and will never “end” because it will just request more input from the user when asked.
- If you did have a file as input to the scanner, calling
hasNext("/0")
is the wrong way to detect the end of the file. You would probably want the unqualified hasNext()
method.
In general, you would read a file in Java using something more like java.io.FileReader
(if reading printable characters - which we would probably wrap in a java.io.BufferedReader
for efficiency) or java.io.FileInputStream
(if reading raw bytes).
If you have a file with the contents you want to print called somefile.txt
in the same directory where the Java binary is running, you can use this to read and print all of the lines until the end of the file:
try (var reader = new BufferedReader(new FileReader("somefile.txt"))) {
reader.lines().forEach(System.out::println);
}
2 Likes
Ohh okk… let me check and try again. thanks jason
Slight tweak to @jmrunkle’s solution…
I think you can do something like this if you need the line numbers:
try (var reader = new BufferedReader(new FileReader("somefile.txt"))) {
int n = 1;
reader.lines().forEach(line -> System.out.printf("%d %s%n", n++, line));
}
3 Likes
thanks dude for the efficient code!