I am a beginner. Reading from text file in Java using a scanner. This code just to read the first 3 tokens isn't working:
try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
System.out.println("Error");
}
I am trying to read just the first 3 tokens:
Andrew#Smith#21
John#Morris#55
the problem occurs when reading 21. java.util.InputMismatchException
The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do
Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.