【问题标题】:How to make output in reverse order using Java language?如何使用Java语言以相反的顺序输出?
【发布时间】:2019-10-06 09:06:48
【问题描述】:

我面临一个问题,从标准输入中取出所有行并将它们以相反的顺序写入标准输出。 即以输入的相反顺序输出每一行。

下面是我的代码:

  import java.util.Scanner;

  public class ReverseOrderProgram {
   public static void main(String args[]) {
    //get input
    Scanner sc = new Scanner(System.in);
    System.out.println("Type some text with line breaks, end by 
    \"-1\":");
    String append = "";
    while (sc.hasNextLine()) {
        String input = sc.nextLine();
        if ("-1".equals(input)) {
            break;
        }
        append += input + " ";
    }
    sc.close();
    System.out.println("The current append: " + append);
    String stringArray[] = append.split(" strings" + "");



    System.out.println("\n\nThe reverse order is:\n");

    for (int i = 0; i < stringArray.length; i++) {

        System.out.println(stringArray[i]);
    }
   }
  }

当我使用如下示例输入运行代码时:

  Type some text with line breaks, end by "-1":
  My name is John.
  David is my best friend.
  James also is my best friend.
  -1

我得到以下输出:

  The current append: My name is John. David is my best friend. James also is my best friend.


  The reverse order is:

  My name is John. David is my best friend. James also is my best friend.

然而,所需的输出如下所示:

  The current append: My name is John. David is my best friend. James also is my best friend.


  The reverse order is:

  James also is my best friend.
  David is my best friend. 
  My name is John.

谁能帮我检查一下我的代码有什么问题并修复它?

【问题讨论】:

    标签: java arrays reverse


    【解决方案1】:

    试试下面的代码。

    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    
    public class ReverseOrderProgram {
    public static void main(String args[]) {
    
        Scanner sc = new Scanner(System.in);
        System.out.println("Type some text with line breaks, end by\"-1\":");
        List<String> list= new LinkedList<String>();
        String append = "";
        while (sc.hasNextLine()) {
            String input = sc.nextLine();
            if ("-1".equals(input)) {
                break;
            }
            list.add(input);
        }
        sc.close();
        System.out.println("The current append: " + append);
    
        Collections.reverse(list);
        for (String string : list) {
            System.out.println(string);
        }
      }
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      而不是将 input 附加到 append 字符串,您应该将输入字符串添加到 List,然后从底部或使用 Collections.reverse() 方法,然后直接打印出来

      【讨论】:

        【解决方案3】:

        编辑 - 与之前的答案基本相同,但使用 for 循环:

        import java.util.ArrayList;
        import java.util.Scanner;
        
        public class ReverseOrderProgram {
            public static void main(String args[]) {
        
            //create arraylist for lines
            ArrayList<String> lines = new ArrayList<String>();
            //get input
        
            Scanner sc = new Scanner(System.in);
            System.out.println("Type some text with line breaks, end by \"-1\":");
            String append = "";
            while (sc.hasNextLine()) {
                String input = sc.nextLine();
                if ("-1".equals(input)) {
                    break;
                }
                lines.add(input);
            }
        
            sc.close();
            System.out.println("The current append: ");
            for(String line : lines){
                System.out.print(line + ". ");
            }
        
            System.out.println("\n\nThe reverse order is:\n");
        
            for (int i = lines.size()-1; i >=0 ; i--) {
                System.out.println(lines.get(i));
            }
        }
        }
        

        【讨论】:

          【解决方案4】:

          1 - 1 种方法是从 backword 运行循环。

          for (int i = stringArray.length; i >=0 ; i++) {
          
              System.out.println(stringArray[i]);
          }
          

          2 - 在列表中使用 Collections.reverse() 方法并打印它。喜欢

              List<String> list = Arrays.asList(stringArray); 
          
              Collections.reverse(list ); 
          
              System.out.println("Modified List: " + list ); 
          

          【讨论】:

            【解决方案5】:

            您可以使用具有 LIFO 行为的 Stack 数据结构来插入和读取元素。更完整的 Java Stack 实现是 Deque,它具有“descendingOrder”方法,该方法以相反的顺序返回元素的迭代器。

                    Deque deque = new LinkedList();
            
                    // We can add elements to the queue in various ways
                    deque.add("Element 1 (Tail)"); // add to tail
                    deque.addFirst("Element 2 (Head)");
                    deque.addLast("Element 3 (Tail)");
                    deque.push("Element 4 (Head)"); //add to head
                    deque.offer("Element 5 (Tail)");
                    deque.offerFirst("Element 6 (Head)");
                    deque.offerLast("Element 7 (Tail)");
            
                    Iterator reverse = deque.descendingIterator();
                    System.out.println("Iterating over Deque with Reverse Iterator");
                    while (reverse.hasNext()) {
                        System.out.println("\t" + reverse.next());
                    }
            
            

            【讨论】:

              【解决方案6】:

              您可以按照其他答案的建议使用Collections.reverse()。但是标准的反转方式是使用Stack 完成的。 Stack 是一个 LIFO 数据结构,它准确地展示了您所需的行为。您需要将所有结果推送到Stackpop,直到Stack 变为empty。像下面 sn-p 这样的东西会给你一个大纲。

              String input = " Hello \n World \n Here you go";
              List<String> inputList = Arrays.asList(input.split("\n"));
                      Stack<String> myStringStack = new Stack<>();
                      myStringStack.addAll(inputList); // This is to exhibit your input scenario from user.
                      while (!myStringStack.isEmpty()) { // While your stack is not empty, keep popping!
                          System.out.println(myStringStack.pop());
                       }
              

              【讨论】:

                猜你喜欢
                • 2023-03-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-06-24
                • 2017-11-27
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多