【问题标题】:Java - printing all ArrayList elements as a single StringJava - 将所有 ArrayList 元素打印为单个字符串
【发布时间】:2015-08-05 05:44:01
【问题描述】:

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

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

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

我的意见:http://prntscr.com/810j6f

getAuthors 是我的驱动程序中分隔作者的方法(在从作者那里获取作者的输入文件中,用“*”分隔而不是用“;”分隔,这是我需要的在我的输出中)

如果信息太少、信息太多、我给出的内容太混乱或者我没有正确解释任何内容,请在 cmets 中告诉我。我是 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;

   }
}

库.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;
   } 
}

【问题讨论】:

  • 您显示的代码没有添加 any 逗号或分号......目前看起来它只会打印“Foo by author1author2”。 (顺便说一句,考虑在循环中使用 StringBuilder 而不是字符串连接。)由于引入了库和书籍,这个问题比它需要的复杂得多 - 如果你只是想弄清楚如何将一组字符串连接在一起,您可以生成一个简短但完整 的程序,该程序除此之外什么都不做,其代码比您在此处显示的要少。相反,我们有不完整的代码,这是不必要的复杂。
  • toString() 默认使用,。自己创建一个字符串并显示出来。
  • 如果您只想将 '*' 替换为 ';' - 你为什么不做theAuthors.replaceAll("\\*", ";");
  • @JonSkeet 是的,我担心有人会这么说。问题是我的程序太复杂了,我无法遵循。即使我创建了一个简单的程序来打印我想要的东西,我也不知道如何在这个程序中打印它。你愿意和我私聊一下,这样我就可以得到这个问题的答案吗?
  • 不,这不是 Stack Overflow 的工作方式。如果你不能从你的项目中提取相关的部分,那是你应该学习的技能。一种选择是创建项目的副本,然后开始删除并非绝对需要演示问题的 所有 代码。那么你至少应该有一些 shorter 和完整的东西。通常,您会发现这足以找出问题所在。

标签: java arraylist printing tostring


【解决方案1】:

所以,我尽我所能并使用了一个可运行的代码示例

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

作为输入,我得到 ​​p>

"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 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将减少混乱并获得更好的响应

【讨论】:

  • 我逐字复制粘贴了您提供的代码,但仍然得到了我的输出。看起来我无法完美地完成这个项目,我现在必须做的事情。不过,感谢您提供的所有帮助,您为可运行示例提供的链接将对我以后的帖子有很大帮助!
  • 在这种情况下,我想知道输入是否是问题...创建一个乐队新项目,没有任何其他类,干净整洁,复制示例代码并输入它运行它,看看你得到了什么
  • 我得去睡觉了,我会考虑一下,作为我校园里的教授,我会回到这个讨论,如果你有兴趣,我会告诉你我发现了什么.
猜你喜欢
  • 2019-05-04
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多