I am inputting a txt file, here is a shortened version
10
"Alexander McCall Smith" "No. 1 Ladies' Detective Agency"
Scanner in = new Scanner(new File(newFile + ".txt"));
int size = in.nextInt();
String inputLine = in.nextLine();
Exception in thread "main" java.util.NoSuchElementException: No line found.
inputLine.
in.next()
inputLine.trim();
int posn = inputLine.indexOf('\"');
int nextPosn = inputLine.indexOf('\"',posn + 1);
String author = inputLine.substring(posn, nextPosn);
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.)