Печать подсписка ArrayList (список дел на основе пользовательского ввода) приводит к пустому ArrayList - PullRequest
0 голосов
/ 08 октября 2018

Очень простой список дел, который запрашивает ввод, а затем распечатывает список в виде ArrayList, разделенного на разделы (подсписки) (у меня действительно плохое зрение, поэтому мне приходится использовать большие шрифты, и когдасписок становится слишком длинным, проблема в том, что конец списка выходит за пределы страницы. Поскольку я могу использовать кнопки «домой» / «конец» для быстрого просмотра страницы, это не оптимальная ситуация. Я бы лучше сломал ArrayListв подсписки и распечатайте подсписки, по одному в каждой строке, как показано ниже:

Вот список текущих дел на сегодня: [Проснись, выгуливай собаку, съешь завтрак] [Убери постель, подмети назад, Изучение Java]

import java.util.Scanner; import java.util.ArrayList;

/**
 * @author Troy
 *
 */
public class HelloWorld {


    public static void main(String[] args) {
        // I chose an ArrayList because the size does not have to be predetermined.
        ArrayList<String> to_do = new<String>ArrayList();
        System.out.println("What would you like to add to your to-do list?");
        Scanner user_input = new Scanner(System.in);
        //While the user_input still has entries, perform the following:
        while (user_input.hasNextLine()) {
            //Add next entry in the to-do list(user_input) to the ArrayList
            String input = user_input.nextLine();
            //If input = remove, remove the last item in the to_do list.(ArrayList)
            if ("remove".equals(input)) {
                if (to_do.size() > 0) {
                to_do.remove(to_do.size() -1);
            }}
            /**If the user types in "exit", when prompted for the next item in their
             * to_do list, close user_input, and print out... 
             */
            if ("exit".equals(input)) {
                user_input.close();
                System.out.println("Your to-do list is complete!");

                ArrayList<String> sect1 = new ArrayList<String>(to_do.subList(0, to_do.size()));                
                if (to_do.size() <= 5) {
                    System.out.println(sect1 + "\n");
                    break;
                }
                ArrayList<String> sect2 = new ArrayList<String>(to_do.subList(6, to_do.size()));
                if (to_do.size() > 5 && to_do.size() <=10) {
                    System.out.println(sect1 + "\n" + sect2);
                    break;
            }
            //If input does NOT equal "remove", add user_input to the to_do list.
                if (!"remove".equals(input)) {
                    to_do.add(input);
                }

            System.out.println("\n");
            /**Print the ArrayList called "to_do" split into sections AFTER writing, 
             * "Here is today's to-do list:"
             *  */
            System.out.println("Here is today's to-do list: " + "\n");
            if (to_do.size() <= 5) {
                System.out.println(sect1 + "\n");
            }
            if (to_do.size() > 5 && to_do.size() <=10) {
                System.out.println(sect1 + "\n" + sect2);
            }

        }
    }
}}

Ответы [ 2 ]

0 голосов
/ 08 октября 2018

Как уже упоминалось в другом постере, проблема с вашим кодом заключается в неправильной вложенности блоков if.Это заставляет ваш to_do.add находиться внутри блока if ("exit".equals(input)), поэтому ваш список остается пустым.Я рекомендую использовать среду IDE и позволить ей заново делать отступы (форматировать) ваш код, тогда эта проблема станет намного более очевидной.

Но помимо этого в вашем коде есть еще одна проблема: ваши sect1 занимаетsubList(0, to_do.size()) это весь ваш список.Это заставит его напечатать весь список в одну строку, что вы и видите.Вместо этого я предлагаю вам использовать цикл и разделить список на равные части.Поскольку subList уже возвращает список, вам также не нужно переносить его в другой ArrayList, и вы можете распечатать его напрямую.

Поэтому я исправил ваш код следующим образом:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

/**
 * @author Troy
 */
public class HelloWorld {
    public static void main(String[] args) {
        // I chose an ArrayList because the size does not have to be predetermined.
        List<String> toDo = new ArrayList<String>();
        System.out.println("What would you like to add to your to-do list?");
        Scanner userInput = new Scanner(System.in);

        // While the userInput still has entries, perform the following:
        while (userInput.hasNextLine()) {
            // Get the next line entered by the user
            String input = userInput.nextLine();

            //If input is "remove", remove the last item in the toDo list. (ArrayList)
            if ("remove".equals(input)) {
                if (toDo.size() > 0) {
                    toDo.remove(toDo.size() -1);
                }
            }
            /*
             * If the user types in "exit", when prompted for the next item in their
             * toDo list, close userInput, and print out... 
             */
            else if ("exit".equals(input)) {
                userInput.close();
                System.out.println("Your to-do list is complete!");
                System.out.println("Here is today's to-do list: ");

                final int perLine = 3;
                int i = 0;
                while(i < toDo.size()) {
                    // Print from the start of our current chunk (i)
                    //  to the end (i+3), or to the size of the list if our last chunk is smaller than "perLine".
                    System.out.println(
                        toDo.subList(i, Math.min(toDo.size(), i+perLine))
                    );
                    i+=perLine;
                }

                break;
            }
            /*
             * If input is neither "remove" nor "exit", add input to the list
             */
            else {
                toDo.add(input);
            }
        }
    }
}

Я также изменил некоторые переменные на camelCase вместо snake_case, как это принято в Java.

0 голосов
/ 08 октября 2018

Проблема заключается в размещении скобок здесь.Линия if (!"remove".equals(input)) { находится внутри блока if ("exit".equals(input)) {.Я переместил операторы if: import java.util.ArrayList;импорт java.util.Scanner;

public class HelloWorld {


    public static void main(String[] args) {
        // I chose an ArrayList because the size does not have to be predetermined.
        ArrayList<String> to_do = new<String>ArrayList();
        System.out.println("What would you like to add to your to-do list?");
        Scanner user_input = new Scanner(System.in);
        //While the user_input still has entries, perform the following:
        while (user_input.hasNextLine()) {
            //Add next entry in the to-do list(user_input) to the ArrayList
            String input = user_input.nextLine();
            //If input = remove, remove the last item in the to_do list.(ArrayList)
            if ("remove".equals(input)) {
                if (to_do.size() > 0) {
                to_do.remove(to_do.size() -1);
            }}

            /**If the user types in "exit", when prompted for the next item in their
             * to_do list, close user_input, and print out... 
             */
            if ("exit".equals(input)) {
                user_input.close();
                System.out.println("Your to-do list is complete!");

                ArrayList<String> sect1 = new ArrayList<String>(to_do.subList(0, to_do.size()));                
                if (to_do.size() <= 5) {
                    System.out.println(sect1 + "\n");
                    break;
                }
                ArrayList<String> sect2 = new ArrayList<String>(to_do.subList(6, to_do.size()));
                if (to_do.size() > 5 && to_do.size() <=10) {
                    System.out.println(sect1 + "\n" + sect2);
                    break;
            }
            //If input does NOT equal "remove", add user_input to the to_do list.
            if (!"remove".equals(input) && !"exit".equals(input)) {
                to_do.add(input);
            }

            System.out.println("\n");
            /**Print the ArrayList called "to_do" split into sections AFTER writing, 
             * "Here is today's to-do list:"
             *  */
            System.out.println("Here is today's to-do list: " + "\n");
            if (to_do.size() <= 5) {
                System.out.println(sect1 + "\n");
            }
            if (to_do.size() > 5 && to_do.size() <=10) {
                System.out.println(sect1 + "\n" + sect2);
            }

        }
    }
}}
...