反向数组结果错误

时间:2017-10-29 17:39:18

标签: java arrays

此代码的结果应为"反向顺序:用户放置的任何10个数字"但我一直得到"反向顺序num反向顺序num以反向顺序num ...."我怎么能改变这个?还有可能将public void reverseNumbersWhile (int num[])方法更改为public void reverseNumbersWhile (int num)吗?我添加了截图以获取更多细节。

import java.util.*;

public class ReverseNumbersFor
{
  public static void main(String[] args) 
  { 
   ReverseNumbersFor reverse = new ReverseNumbersFor();
   reverse.setArray();
  } // end of main

  public void setArray()
  {
    int num [] = new int [10];
    reverseNumbersWhile(num);

  } 

    public void printArray (int num[])
    {
      for (int i = num.length - 1; i >=0; i--)
      {
        System.out.print("In reverse order : " + num[i] + " ");
      }
    }

    public void reverseNumbersWhile (int num[])
    {
      Scanner input = new Scanner (System.in);
      System.out.print("Enter 10 numbers : ");

      int temp;
      int [] in = num;
      for (int i = 0; i < num.length; i++)
      {
        in [i] = input.nextInt();
      }
      printArray(num);         
    }     
}

Image of result

1 个答案:

答案 0 :(得分:0)

编辑你打印Array方法如下, 错误是result = (num[i] + " ");它应该是result += (num[i] + " ");,或者如果您喜欢result = result + (num[i] + " ");

只需将其写为

即可
public void printArray (int num[])
{
  for (int i = num.length - 1; i >=0; i--)
  {
    System.out.print(num[i] + " ");  

  }
}