-2

我正在尝试将用户编号输入从右向左移动。除了没有注册第一个号码外,它似乎正在工作。我认为因为对于反向部分,我的计数是 1。我尝试使用 0,反之亦然,但它会导致错误。关于如何转移用户数量的任何想法?所需的输出与用户输入的相反。示例:用户输入 3 个数字。3.0 2.0 1.0。反向 1.0。2.0。3.0。

// import Scanner 
import java.util.Scanner;
public class Arrays {


   public static void main (String [] args){

      int count=0;

      //introduce Scanner
      Scanner input = new Scanner(System.in);
      //printout question asking for user input and use count as input variable
      System.out.println("Please input the size of array");
      count=input.nextInt();
      //create array and connect count to it
      double[] numbers = new double [count];

      System.out.println("Please input  "+ numbers.length+ " double numbers");
      //create for loop for original number order

      for ( count=0; count<numbers.length; count++){

         numbers[count] = input.nextDouble(); 

         System.out.print( +numbers[count] + "  ");     

      }

      //print out the reverse order
      System.out.print("\n After Reverse Order " );

      //create for loop for reversed number order
      for (count =  1;  count< numbers.length; count++){

         numbers[count-1]=numbers[count];

         System.out.println ( "\n"+ numbers[count] );   

      }



   } 
}
4

2 回答 2

0

如果你想颠倒元素的顺序,那就是 REVERSE ORDER 而不是 SHIFT。正确的“移位”会将它们全部向右或向左移动,要么丢弃末端元素,要么(可能)将其旋转到另一端。

所以第一件事是,要知道你实际上在说什么。

反转数组中整数的顺序:

int i = 0;
int j = numbers.length - 1;   // corresponding index at opposite end of array.

// stop when half the array has been swapped.. with the other half.
while (i < j) {               
    // swap between ends.
    int swap = numbers[i];
    numbers[i] = numbers[j];
    numbers[j] = swap;

    // advance indices.
    i++;  j--;
}
于 2013-07-15T02:05:33.660 回答
0

尝试这个:

Double[] numbers = new Double[count];
...
Collections.reverse(Arrays.asList(numbers));
于 2013-07-15T03:40:46.760 回答