1
/* txt file
Rolling Stone#Jann Wenner#Bi-Weekly#Boston#9000
Rolling Stone#Jann Wenner#Bi-Weekly#Philadelphia#8000
Rolling Stone#Jann Wenner#Bi-Weekly#London#10000
The Economist#John Micklethwait#Weekly#New York#42000
The Economist#John Micklethwait#Weekly#Washington#29000
Nature#Philip Campbell#Weekly#Pittsburg#4000
Nature#Philip Campbell#Weekly#Berlin#6000
*/   


 public class Zines {

            public static void main(String[] args) throws FileNotFoundException {
                Scanner input = new Scanner(new File("txt.file"));
                input.useDelimiter("#|\n|\r|\r\n");

                while(input.hasNext()) {  
                    String title = input.next();
                    String author = input.next();
                    String publisher = input.next();
                    String city = input.next();
                    String line = input.nextLine();
                    //int dist = Integer.valueOf(line);

                    System.out.println(line); 
        }
        }
    }

输出是:

"#9000
"#8000
"#10000
"#42000
"#29000
"#4000
"#6000  

输出 2:

9000
Rolling Stone
("Exception in thread "main") Jann Wenner
Weekly
Washington
4000
Nature
4

1 回答 1

0

这里的问题是为什么在使用分隔符后仍然会出现#?

因为您正在Scanner#nextLine()阅读最后一部分。它不会考虑分隔符。它将在先前读取的令牌之后读取完整的剩余文本,而不是下一个令牌。

因此,如果先前读取的标记是Boston,则剩余的文本 -#9000将由 读取nextLine()。你应该scanner#next()改用。

String line = input.next();
于 2013-08-17T20:16:12.610 回答