拆掉这个字符串?

时间:2012-12-10 07:15:08

标签: java string

我有一个外部文本文件:

-To Kill a Mockingbird by Harper Lee.
-The Great Gatsby by Scott Fitzgerald.
-Hamlet by William Shakespeare.
-Then Catch in the Rye by J.D Salinger.
-One Hundred Years of Solitude by Gabriel Garcia Marquez.
-The Hobbit by J.R.R Tolkien.
-Moby Dick by Herman Melville.
-A Tale of two Cities by Charles Dickens.
-Don Quixoteby Miguel de Cervantes.
-Love in the Time of Cholera by Gabriel Garcia Marquez.
-Of Mice and Men by John Steinbeck.
-Fahrenheit 451 by Ray Bradbury.
-Stranger in a Strange Land by Robert Heinlein.
-Siddartha by Herman Heese.
-Atlas Shrugged by Ayn Rand.
-The Count of Monte Cristo by Alexandre Dumas.
-The Iliad by Homer.
-The Odyssey by Homer.
-A Wrinkle in Time by Madeleine L'Engle.
-Inferno by Dante Alighieri.
-Paradise Lost by John Milton.
-Alice's Adventures in Wonderland by Lewis Carroll.
-War and Peace by Leo Tolstoy.
-Frankenstein by Mary Shelley.
-Romeo and Juliet by William Shakespeare.
-Exodus by Leon Uris.
-1984 by George Orwell.

我想要做的是分割每一行的字符串并将它们存储在一个arraylist上 我只是不知道为什么它在读取这个文本文件时从第一行跳到第三行: 我的代码:

bookSearch = new Scanner(new FileInputStream("src/booksNames.txt")).useDelimiter(" by ");
            books = new ArrayList<Books>();
            String storeName = "";
            String storeAuthor = "";

            while(bookSearch.hasNextLine())
            {

                storeName = bookSearch.next().split("by")[0];
                storeAuthor = bookSearch.next().split("(by)|(\\.)")[0];

                bookSearch.nextLine();              

                info = new Books(storeName, storeAuthor);
                books.add(info);
            }

我得到的是由Harper Lee杀死一只嘲笑鸟,然后由William Shakespeare跳到哈姆雷特!它只是忽略了第二,第四,第六行等等..... 任何帮助将不胜感激!!

每个标题和作者都是一个单独的行!

6 个答案:

答案 0 :(得分:3)

你在loop.bookSearch.nextLine()里面两次调用bookSearch.next(),每次都跳到下一个对象。

while(bookSearch.hasNextLine())
            {

                storeName = bookSearch.next().split("by")[0]; 
                storeAuthor = bookSearch.next().split("(by)|(\\.)")[0]; // The error lies here, bookSearch.next() skips to the next object every time

                bookSearch.nextLine();              

                info = new Books(storeName, storeAuthor);
                books.add(info);
            }

正确实施:

while(bookSearch.hasNextLine())
            {
                String bookString = bookSearch.nextLine();
                storeName = bookString.split("by")[0];
                storeAuthor = bookString.split("by")[1];

                info = new Books(storeName, storeAuthor);
                books.add(info);
            }

答案 1 :(得分:2)

这是因为您在bookSearch.next()循环

中两次致电while

答案 2 :(得分:1)

您已在循环内调用bookSearch.next()两次,并在bookSearch.nextLine()调用一次。

  

查找并返回此扫描仪的下一个完整令牌。在完成令牌之前和之后是与分隔符模式匹配的输入。即使之前的hasNext()调用返回true,此方法也可能在等待输入扫描时阻塞。

while(bookSearch.hasNextLine())
{
      String[] book = bookSearch.next();
      storeName = book.split("by")[0];
      storeAuthor = book.split("(by)|(\\.)")[1];
      info = new Books(storeName, storeAuthor);
      books.add(info);
}

答案 3 :(得分:0)

使用类似的东西

try{
        FileReader fr=new FileReader("Test.txt");
        BufferedReader br=new BufferedReader(fr);

        while((str=br.readLine()) != null){
        strBuf.append(str);
                //here you can add the str to your arrayList

        }
        }catch(Exception e){

        }

此处Test.txt是您的输入文件。此代码段将逐行获取

来自文本文件。

希望这就是你要找的东西

答案 4 :(得分:0)

您可以使用以下代码来读取文件。您还应该考虑以下事项。

  • 您应首先检查它是否包含“by”关键字,因为有一行不包含“by”,例如“Don Quixoteby Miguel de Cervantes。”。
  • 你应该使用“by”关键字之间的空格进行拆分,因为“Gatsby”也包含“by”,它也会拆分它并给你错误的结果。

    public void readFile(String fileName) {
    DataInputStream in = null;
    try {
        in = new DataInputStream(new FileInputStream(new File(fileName)));
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    
        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains(" by ")) {
                String[] arr = line.split(" by ");
                String book = arr[0];
                String author = arr[1];
    
                System.out.println("Book : " + book + " Author : " + author + "\n");
                System.out.println("\n");
            } else {
                System.out.println(line + "\n");
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
    

答案 5 :(得分:0)

那里你大概有90%。需要注意的一点是String.split()返回的内容 - 它会返回一个String数组,您可以正确记录它。但是,如果您为正在阅读的每一行创建数组并以此方式执行处理,那么您将获得更好的服务。

此外,您正在拨打next()两次。回想一下Scanner.next()实际上做了什么 - 最好是创建局部变量来保存String或分割String[]

相关问题