TeenCoder TeenCoder - 11 months ago 67
Java Question

No Line Found - Java

I am inputting a txt file, here is a shortened version

10
"Alexander McCall Smith" "No. 1 Ladies' Detective Agency"


I run this code:

Scanner in = new Scanner(new File(newFile + ".txt"));
int size = in.nextInt();
String inputLine = in.nextLine();


size ends up being 10, but inputLine ends up receiving nothing. I get the error

Exception in thread "main" java.util.NoSuchElementException: No line found.


I went to debugger and it says a string with position (-1, -1) is what java tries to insert into
inputLine.
I have no clue why, I know there is 50+ lines of text after 10. I ran
in.next()
and it worked just fine. Does anyone know why?

I run this code as well:

inputLine.trim();
int posn = inputLine.indexOf('\"');
int nextPosn = inputLine.indexOf('\"',posn + 1);
String author = inputLine.substring(posn, nextPosn);

Answer Source

Andrew Li has it right. Calling nextInt does not consume the line, so you're still on the first line, the one with "10" on it.

public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(Test.class.getResourceAsStream("input.txt"));
    int size = in.nextInt();
    String inputLine = in.nextLine();
    System.out.println(size); // prints "10"
    System.out.println(inputLine); // prints nothing

    inputLine.trim();
    int posn = inputLine.indexOf('\"');
    int nextPosn = inputLine.indexOf('\"', posn + 1);
    String author = inputLine.substring(posn, nextPosn); // Throws: "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
}

If you were to call nextLine twice in a row, you would get the "Alexander" line.

(I have no idea where you're getting a NoSuchElementException. It must be from somewhere else in your program.)