Java - 将所有ArrayList元素打印为单个String

时间:2015-08-05 05:44:01

标签: java arraylist printing tostring

我的程序打印出一个库。每个图书馆都由书籍组成。每本书都由标题和该书的作者组成。我有一个驱动程序,一个Library类和一个Book类。我的问题是,当我使用我的驱动程序在库中使用我的toString()方法并预订类来打印库时,每本书的作者都显示为[author, ;, author, ;, author],我希望它们打印为author; author; author

预期输出:http://prntscr.com/810ik2

我的输出:http://prntscr.com/810ipp

我的输入:http://prntscr.com/810j6f

getAuthors是我的驱动程序中用于分隔作者的方法(在输入文件中,作者从作者处获取的是由' *'而不是由...分隔';'这是我在输出中需要的内容)

如果信息太少,信息太多,如果我提供的内容过于混乱,或者我没有正确解释,请在评论中告诉我。我是Java的新手,在这里发布问题还不错,所以请放轻松。谢谢!

编辑:以防这里是我的三个班级(只有重要的东西):

Book.java:

import java.util.*;

public class Book implements Comparable<Book>
{

   private final String myTitle;
   private final ArrayList<String> myAuthors;

   public Book(final String theTitle, final ArrayList<String> theAuthors)
   {
      if (theTitle == "" || theAuthors.isEmpty() ||
          theTitle == null || theAuthors.get(0) == null)
      {
         throw new IllegalArgumentException(
         "The book must have a valid title AND author.");
      }
      else
      {
         myTitle = theTitle;
         myAuthors = new ArrayList<String>();
         for (int i = 0; i < theAuthors.size(); i++)
         {
            myAuthors.add(theAuthors.get(i));
         }
      }
   }

   public String toString() 
   { 
      String result = "\"" + myTitle + "\" by ";

      for (int i = 0; i < myAuthors.size(); i++)
      {
         result += (String)myAuthors.get(i);
      }
      return result;

   }
}

Library.java:

import java.util.*;
public class Library
{

   public Library(final ArrayList<Book> theOther)
   {
      if (theOther == null)
      {
         throw new NullPointerException();
      }
      else
      {
         myBooks = new ArrayList<Book>();
         for (int i = 0; i < theOther.size(); i++)
         {
            myBooks.add(theOther.get(i));
         }
      }
   }

   public ArrayList<Book> findTitles(final String theTitle)
   {
      ArrayList<Book> titleList = new ArrayList<Book>();
      for (int i = 0; i < myBooks.size(); i++)
      {
         if (myBooks.get(i).getTitle().equals(theTitle))
         {
            titleList.add(myBooks.get(i));
         }
      }
      return titleList;
   }

   public String toString()
   {
      String result = "";
      for (int i = 0; i < myBooks.size(); i++)
      {

         String tempTitle = myBooks.get(i).getTitle();
         ArrayList<String> tempAuthors = myBooks.get(i).getAuthors();
         Book tempBook = new Book(tempTitle, tempAuthors);
         result += (tempBook + "\n");
      }
      return result;
   }
}

LibraryDriver.java:

import java.util.*;
import java.io.*;

public class LibraryDriver
{
   public static void main(String[] theArgs)
   {
      Scanner inputFile = null;
      PrintStream outputFile = null;
      ArrayList<String> authors = new ArrayList<String>();
      ArrayList<Book> books = new ArrayList<Book>();
      ArrayList<Book> books2 = new ArrayList<Book>();

      String[] filesInputs = new String[]{"LibraryIn1.txt", "LibraryIn2.txt"};

      try 
      { 
         outputFile = new PrintStream(new File("LibraryOut.txt")); 
         for (String fileInput : filesInputs) 
         { 
            inputFile = new Scanner(new File(fileInput)); 
            while (inputFile.hasNext()) 
            { 
               String title = ""; 
               String input = inputFile.nextLine(); 
               //Read title 
               title = input; 
               input = inputFile.nextLine(); 
               authors = getAuthors(input); 

               //Insert title & authors into a book 
               Book tempBook = new Book(title, authors); 
               //Add this book to the ArrayList<Book> of books 
               books.add(tempBook); 

            } 
            Library myLib = new Library(books);
            outputFile.println(myLib);
            inputFile.close(); 
            myLib.sort();
            outputFile.println(myLib);
         } 
      } 
      catch (Exception e) 
      { 
         System.out.println("Difficulties opening the file! " + e); 
         System.exit(1); 
      }
      inputFile.close();
      outputFile.close();
   }
   public static ArrayList<String> getAuthors(String theAuthors)
   {
      int lastAsteriskIndex = 0;
      ArrayList<String> authorList = new ArrayList<String>();
      for (int i = 0; i < theAuthors.length(); i++)
      {
         if (theAuthors.charAt(i) == '*')
         {
            if (lastAsteriskIndex > 0)
            {
               authorList.add(";");
               authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
            }
            else
            {
               authorList.add(theAuthors.substring(0, i));
            }
            lastAsteriskIndex = i;
         }
      }
      if (lastAsteriskIndex == 0)
      {
         authorList.add(theAuthors);
      }
      return authorList;
   } 
}

1 个答案:

答案 0 :(得分:0)

所以,我尽可能地使用

将一个可运行的代码示例混合在一起
The Hobbit
Tolkien, J.R.R
Acer Dumpling
Doofus, Robert

作为输入,我得到了

"The Hobbit" by Tolkien, J.R.R
"Acer Dumpling" by Doofus, Robert

代码:

import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;

public class LibraryDriver {

    public static void main(String[] theArgs) {

//      ArrayList<Book> books = new ArrayList<>(25);
//      books.add(
//                      new Book("Bananas in pajamas", 
//                                      new ArrayList<>(Arrays.asList(new String[]{"B1", "B2"}))));
//      
//      Library lib = new Library(books);
//      System.out.println(lib.toString());
        Scanner inputFile = null;
        PrintStream outputFile = null;
        ArrayList<String> authors = new ArrayList<String>();
        ArrayList<Book> books = new ArrayList<Book>();
        ArrayList<Book> books2 = new ArrayList<Book>();

        String[] filesInputs = new String[]{"LibraryIn1.txt"}; //, "LibraryIn2.txt"};

        try {
            outputFile = new PrintStream(new File("LibraryOut.txt"));
            for (String fileInput : filesInputs) {
                inputFile = new Scanner(new File(fileInput));
                while (inputFile.hasNext()) {
                    String title = "";
                    String input = inputFile.nextLine();
                    //Read title 
                    title = input;
                    input = inputFile.nextLine();
                    authors = getAuthors(input);

                    //Insert title & authors into a book 
                    Book tempBook = new Book(title, authors);
                    //Add this book to the ArrayList<Book> of books 
                    books.add(tempBook);

                }
                Library myLib = new Library(books);
                outputFile.println(myLib);
                inputFile.close();
//              myLib.sort();
//              outputFile.println(myLib);
            }
        } catch (Exception e) {
            System.out.println("Difficulties opening the file! " + e);
            System.exit(1);
        }
        inputFile.close();
        outputFile.close();
    }

    public static ArrayList<String> getAuthors(String theAuthors) {
        int lastAsteriskIndex = 0;
        ArrayList<String> authorList = new ArrayList<String>();
        for (int i = 0; i < theAuthors.length(); i++) {
            if (theAuthors.charAt(i) == '*') {
                if (lastAsteriskIndex > 0) {
                    authorList.add(";");
                    authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
                } else {
                    authorList.add(theAuthors.substring(0, i));
                }
                lastAsteriskIndex = i;
            }
        }
        if (lastAsteriskIndex == 0) {
            authorList.add(theAuthors);
        }
        return authorList;
    }

    public static class Library {

        private ArrayList<Book> myBooks;

        public Library(final ArrayList<Book> theOther) {
            if (theOther == null) {
                throw new NullPointerException();
            } else {
                myBooks = new ArrayList<Book>();
                for (int i = 0; i < theOther.size(); i++) {
                    myBooks.add(theOther.get(i));
                }
            }
        }

        public ArrayList<Book> findTitles(final String theTitle) {
            ArrayList<Book> titleList = new ArrayList<Book>();
            for (int i = 0; i < myBooks.size(); i++) {
                if (myBooks.get(i).getTitle().equals(theTitle)) {
                    titleList.add(myBooks.get(i));
                }
            }
            return titleList;
        }

        public String toString() {
            String result = "";
            for (int i = 0; i < myBooks.size(); i++) {

                String tempTitle = myBooks.get(i).getTitle();
                Book b = myBooks.get(i);
                ArrayList<String> tempAuthors = b.getAuthors();
                Book tempBook = new Book(tempTitle, tempAuthors);
                result += (tempBook + "\n");
            }
            return result;
        }
    }

    public static class Book implements Comparable<Book> {

        private final String myTitle;
        private final ArrayList<String> myAuthors;

        public Book(final String theTitle, final ArrayList<String> theAuthors) {
            if (theTitle == "" || theAuthors.isEmpty()
                            || theTitle == null || theAuthors.get(0) == null) {
                throw new IllegalArgumentException(
                                "The book must have a valid title AND author.");
            } else {
                myTitle = theTitle;
                myAuthors = new ArrayList<String>();
                for (int i = 0; i < theAuthors.size(); i++) {
                    myAuthors.add(theAuthors.get(i));
                }
            }
        }

        public String toString() {
            String result = "\"" + myTitle + "\" by ";

            for (int i = 0; i < myAuthors.size(); i++) {
                result += (String) myAuthors.get(i);
            }
            return result;

        }

        @Override
        public int compareTo(Book o) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        public String getTitle() {
            return myTitle;
        }

        public ArrayList<String> getAuthors(String theAuthors) {
            int lastAsteriskIndex = 0;
            ArrayList<String> authorList = new ArrayList<String>();
            for (int i = 0; i < theAuthors.length(); i++) {
                if (theAuthors.charAt(i) == '*') {
                    if (lastAsteriskIndex > 0) {
                        authorList.add(";");
                        authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
                    } else {
                        authorList.add(theAuthors.substring(0, i));
                    }
                    lastAsteriskIndex = i;
                }
            }
            if (lastAsteriskIndex == 0) {
                authorList.add(theAuthors);
            }
            return authorList;
        }

        public ArrayList<String> getAuthors() {
            return myAuthors;
        }
    }
}

考虑提供展示您问题的runnable example。这不是代码转储,而是您正在做的事情的一个示例,它突出了您遇到的问题。这将减少混淆和更好的响应