dimitris25 dimitris25 - 6 months ago 38
Java Question

How to print Strings from a file with specific way in java?

I have this file with name "examples.txt" with data

a1 b4

a7 b6

a3 b9

and I want to print from every line every string separately for example
a1 b4
Ι wrote this code

try
{
FileInputStream inputStream = new FileInputStream("example.txt");
}
catch (FileNotFoundException e)
{
System.out.println("Problem opening file.");
System.exit(0);
}
Scanner inputReader = new Scanner(inputStream);
while (inputReader.hasNextLine())
{
System.out.println(inputReader.next());
System.out.println(inputReader.next());
}


This code does exactly what I want, print all data until last line, but it causes a run-time error java.util.NoSuchElementException and I don't understand why. Is there any solution to this problem ?

Answer

What you are looking for is this:

// Iterate as long as you have remaining lines
while (inputReader.hasNextLine()) {
    String line = inputReader.nextLine();
    // For each line, slip the tokens using space as separator
    for (String token : line.split(" ")) {
        System.out.println(token);
    }
}

Output:

a1
b4
a7
b6
a3
b9

Response update:

Actually your code also works, the problem that you face is probably due to an empty line at the end of your file, indeed as it is a line hasNextLine() will return true but since there is no more token left it throws NoSuchElementException. With my approach you don't have this problem because an empty line will return an empty array.