Scanner s = new Scanner(new File("src/mail_list"));
while (s.hasNextLine()){
String line1 = s.nextLine();
if (line1.startsWith("Users")){
line1 = s.nextLine();
while (!(line1 = s.nextLine()).isEmpty()) {
String arr[] = line1.split(" ", 4);
users.add(new User(arr[0],arr[1],arr[2],arr[3]));
}
}
if (line1.startsWith("Lists")){
line1 = s.nextLine();
while (!(line1 = s.nextLine()).isEmpty()) { //exception here
String arr1[] = line1.split(" ", 2);
ArrayList<String> tmp = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(arr1[1]);
while (st.hasMoreTokens()) {
tmp.add(st.nextToken());
}
list.add(new List((arr1[0]), tmp));
}
}
}
/*-testfile-start*/
Keyword: Users
username1 Name1 Surname1 email1
username2 Name2 Surname2 email2
Keyword: Lists
list_name username1 username2 ...
/*-testfile-end*/
I'm using the above code in order to sort things from the above testfile pattern. Basically it means that if I encounter the keyword "Users" I have to add the said info about the user.
I marked in the code where the exception rises. Any ideas on how to counter it?
You are calling nextLine()
twice but only checking hasNextLine()
once.
String line1 = s.nextLine();
if (line1.startsWith("Users")){
line1 = s.nextLine();
Meaning you are getting the next line without knowing if there is one, which throws the exception if there isn't one.
I found a stupid solution to it. I just added a 'dummy' char 2 lines after the last line. and it works. It's not a perfect solution but since the testfile is not meant to be seen by any1 i'll take it for now... Thank's everybody who brainstormed with me for this 45 mins.
Do!(line1 = s.nextLine())!= null,不为空,因为它无法读取空行。
From Scanner#nextLine
:
Throws:
NoSuchElementException
- if no line was found.
And you have this code:
while (s.hasNextLine()) {
//checked if there's line to read
String line1 = s.nextLine();
if (line1.startsWith("Users")) {
//not checked if there's line to read
line1 = s.nextLine();
//not checked here either
while (!(line1 = s.nextLine()).isEmpty()) {
String arr[] = line1.split(" ", 4);
users.add(new User(arr[0],arr[1],arr[2],arr[3]));
}
}
//similar in code below...
}
Make sure to validate there's a line to be read before using Scanner#nextLine
. Handle the exceptions accordingly.
As you can see, this method throws NoSuchElementException when no line was found.
if (line1.startsWith("Lists")){
line1 = s.nextLine(); // <=============== ?
while (!(line1 = s.nextLine()).isEmpty()) { //exception here
How do you know that you have more lines there and in your comment line?
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.