簡體   English   中英

如何按正常順序打印然后反轉?

[英]How Print in normal order and then reverse it?

我必須輸入一個數組的長度,如何以正常順序打印數字然后反轉它!

例:

輸入數組的長度:3
輸入int 1:56
輸入INT 2:10
輸入INT 3:20
正常56
10
20
相反
20
10
56

import java.util.Scanner;


 {
  public static void main(String[] args)
  {
   int ArrayL;    

   // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);


    System.out.print("Enter the length of the   array: ");
    ArrayLh= keyboard.nextInt();

     // Create an array 
    double[] array = new double[ArrayL];

       for (int index = 0; index < ArrayL; index++)
   {
     System.out.print("Enter Int" +
                     (index + 1) + ": ");
     array[index] = keyboard.nextDouble();
   }    
  }
 }
   for(int i=0; i<ArrayLength;i++){
    System.out.println(array[i]);
   }

for(int i=ArrayLength-1; i>=0; i--){
    System.out.println(array[i]);
}

在Java 8中,您可以這樣做:

    List<Double> list1 = Arrays.stream(arrays).boxed().collect(Collectors.toList());
    System.out.println(list1);
    List<Double> list2 = new ArrayList<Double>(list1);
    Collections.reverse(list2);
    System.out.println(list2);

如果需要將元素與空間連接起來,請使用以下命令:

    String forwardText = list1.stream().map(Object::toString).collect(Collectors.joining(" "));
    System.out.println(forwardText);
    String backwardText = list2.stream().map(Object::toString).collect(Collectors.joining(" "));
    System.out.println(backwardText);

打印正常訂單:

Arrays.stream(array).forEach(System.out::println);

打印反向訂單:

Arrays.stream(array).boxed()
                .collect(Collectors.toCollection(ArrayDeque::new))
                .descendingIterator().forEachRemaining(System.out::println);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM