【问题标题】:Is there a way to have multiple lines of text in one array element for Java? [closed]有没有办法在 Java 的一个数组元素中包含多行文本? [关闭]
【发布时间】:2017-01-02 21:37:49
【问题描述】:

为一个学校项目创建一个测验,如果有一种方法可以在数组的一个元素中包含一个问题和 4 个可能的答案,并且问题和 4 个可能的答案都处于打开状态,这将使代码变得更容易他们自己的路线。

【问题讨论】:

  • 你问的是如何制作多行字符串?
  • 基本上是的,它们都位于单个数组元素中
  • 您似乎完全忽略了 Java 是一种面向对象语言的事实。不要创建一个字符串数组,其中每个字符串都必须被解析以将问题与其答案分开。创建一个 Question 对象数组,其中 Question 对象将有一个字段 question,或类型为 String,以及一个字段 possibleAnswers,类型为 String[],例如。
  • 我认为您正在寻找 '\n' 字符。例如String[] questions = {"Is a = b?\na. Yes.\nb.No\nc.\n\nDepends", "Why?\na. 因为\nb. 因为不是"};

标签: java arrays eclipse


【解决方案1】:

如果您创建String[]String 对象的数组),则该数组中的每个元素都可以包含任何有效的 Java String,其中包括一个包含换行符 \n 的字符串。因此,您可以将每个数组元素设为多行字符串,每行由\n 字符分隔,以便在第一个\n 之前找到问题,在第二个\n 之前找到正确答案,并且不正确的答案在随后的“行”中找到。

但是,我想说这实际上使代码更加神秘,因此难以理解。一种更好的面向对象的方法是创建一个代表测验问题及其答案的新类。此类的大纲可能如下所示:

class QuizQuestion {
    String questionText;
    String correctAnswer;
    List<String> incorrectAnswers;
}

您可以完全像这样离开这个类,并简单地引用它的类字段(从同一个代码包中),从而创建一个新的对象类型,它将问题文本和答案很好地捆绑在一起。或者,如果需要,您可以向此类添加方法,以控制/保护访问/修改类字段数据的方式。

现在,您可以使用List&lt;QuizQuestion&gt;QuizQuestion[],而不是使用您原来的String[]。这应该使代码更易于阅读,并且将来更易于增强。

【讨论】:

    【解决方案2】:

    尽管以上所有答案都是您问题的有效实现,但我宁愿采用 JB Nizet 在上面的 cmets 中所述的面向对象的方法。这是一个示例程序,它实现了一个测验并显示了一个面向对象的实现。请不要将其 1:1 复制作为作业的解决方案。它应该提供一些示例,说明您可以使用 Java 或任何其他面向对象的语言做什么......

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    /**
     * Quiz is a "wrapper class" for your whole project. 
     * It contains a set of questions and some helper methods
     * to create the questions and proper answers.
     */
    public class Quiz {
    
        /**
         * We use a list to store our questions. 
         * Each question is an object of type "Question"
         */
        List<Question> questions = new ArrayList<>();
    
        /**
         * The entry point for our program. 
         * Java will run this method, if our code is "started".
         *
         * All it does is
         *
         * 1. Create a new quiz
         * 2. Start the quiz with the 'play' method
         */
        public static void main(String[] args) {
            Quiz quiz = Quiz.create();
            quiz.play();
        }
    
        /**
         * Helper method to create a quiz. 
         * You can add as many questions as you like with as many answers 
         * as you like.
         * The second parameter indicates the index of the answer 
         * that is the expected answer (starting with 1, not with 0).
         */
        public static Quiz create() {
            Quiz quiz = new Quiz();
            quiz.addQuestion(
                    "What is the heaviest animal on earth?",
                    3,
                    "Elephant",
                    "Cow",
                    "Whale",
                    "Crocodile"
            );
            quiz.addQuestion(
                    "What is the biggest planet in the solar system?",
                    2,
                    "Mars",
                    "Jupiter",
                    "Earth",
                    "Saturn"
            );
            return quiz;
        }
    
        /**
         * Helper method that actually starts our quiz.
         *
         * There is a lot of room for improvement here - I just wanted 
         * to give you a brief example
         * of how you can use the code here to play the quiz. Feel free to change :)
         */
        public void play() {
            for (Question q : questions) {
                System.out.println(q.getQuestion());
                int i = 1;
                for (Answer a : q.getAnswers()) {
                    System.out.println(i++ + ". " + a.getAnswer());
                }
                System.out.printf("Please tell me the correct answer: ");
                Scanner in = new Scanner(System.in);
                String givenAnswer = in.next();
                if (q.getExpectedAnswer() == Integer.parseInt(givenAnswer)) {
                    System.out.printf("Brilliant - your answer was correct!");
                } else {
                    System.out.println("Ooops - that was wrong. The expected answer was: " + q.getProperAnswer());
                }
            }
        }
    
        /**
         * Helper method that adds a question to the quiz.
         *
         * First parameter is the question itself.
         * Second parameter is the index of the correct answer 
         *   in the answers given in the third parameter.
         *   Mind that the index starts with 1 not with 0 as arrays do in Java.
         * Third parameter is a variable length parameter: 
         *   this enables you to add as many answers as you want.
         */
        private void addQuestion(String questionText, int expectedAnswer, String... answers) {
            Question question = new Question(questionText);
            for (String answerText : answers) {
                question.addAnswer(new Answer(answerText));
            }
            question.setExpectedAnswer(expectedAnswer);
            this.questions.add(question);
        }
    
        /**
         * Class that implements a question.
         *
         * A question consists of the text for the question itself,
         * the index of the expected answer (starting with 1!) and
         * an ordered list of answers.
         */
        public class Question {
    
            private String question;
    
            private int expectedAnswer;
    
            private List<Answer> answers = new ArrayList<>();
    
            public Question(String question) {
                this.question = question;
            }
    
            public void addAnswer(Answer answer) {
                answers.add(answer);
            }
    
            public void setExpectedAnswer(int expectedAnswer) {
                this.expectedAnswer = expectedAnswer;
            }
    
            public int getExpectedAnswer() {
                return expectedAnswer;
            }
    
            public String getQuestion() {
                return question;
            }
    
            public List<Answer> getAnswers() {
                return answers;
            }
    
            public String getProperAnswer() {
                return answers.get(expectedAnswer - 1).getAnswer();
            }
        }
    
        /**
         * The answer itself is again a class.
         *
         * This is a little over-engineered, it might as well be a string.
         * Implementing it as a separate class enables you to add further 
         *   information - e.g. a scoring for the wrong / right answer...
         */
        private class Answer {
    
            private String answer;
    
            public Answer(String answer) {
                this.answer = answer;
            }
    
            public String getAnswer() {
                return answer;
            }
    
        }
    
    }
    

    如果您对实施有任何疑问,请随时在 cmets 中向我提问。快乐编码!

    【讨论】:

      【解决方案3】:

      您可以在字符串中放置一个行分隔符。为确保程序在任何平台上都能正常运行,您应该使用%n 格式化程序和printf 您的字符串:

      String[] questions = new String[] {
          // Question #1 with its answers
          "What is your name?%n" +
          "%n"                   +
          "1. Stack%n"           +
          "2. Overflow%n"        +
          "3. John%n"            +
          "4. Doe%n"
      
          // More questions here..
      };
      
      for (String question : questions) {
          System.out.printf(question);
      }
      

      【讨论】:

      • @hardillb %n 是一个平台中立的格式化程序,用于将 printf 替换为正确的换行符。
      • 您确定必须使用 '+' 吗?我认为它必须是 ' , ' 而不是 ' + ' ...
      • @Mohsen_Fatemi 这是数组的一个元素,为了便于阅读,分成多个字符串。您应该在数组的不同元素之间使用,
      • @Mureinik 使用这种方法,在输出下一个问题之前如何检查每个答案?
      【解决方案4】:

      基本上,您需要做的就是在字符串中添加一个分隔符并在显示问题时对其进行评估。

      String question = "Question\0First Answer\0Second Answer\n with Linebreak\0Third Answer";
      

      单独使用split():

      String[] questionAndAnswers = question.split("\0");
      

      但这不是应该的工作方式。您应该创建一个具有问题和可能答案属性的Question 对象。然后构建一个 Question 对象数组,而不是 String

      public class Question {
           private String question;
           private String[] answers;
           private int correct;
      
           // have getters and setters here 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 1970-01-01
        • 2019-03-21
        相关资源
        最近更新 更多