在Java中使用for循环反转数组。

huangapple go评论102阅读模式
英文:

Reverse array with for loop in Java

问题

以下是您提供的代码的翻译部分:

我想知道您是否可以帮助我处理这段代码。它应该颠倒数组的内容,但我得到了这个结果。是否有人知道如何修复这个问题?

  1. import java.util.Arrays;
  2. public class Arrays7 {
  3. public static void main(String[] args) {
  4. // 编写一个Java程序来颠倒整数值的数组。
  5. int arr[] = { 1, 2, 3, 4, 5};
  6. int petlja[] = { 0, 0, 0, 0, 0 };
  7. /* arr[0] = petlja[4];
  8. arr[1] = petlja[3];
  9. arr[2] = petlja[2];
  10. arr[3] = petlja[1];
  11. arr[4] = petlja[0];
  12. */
  13. for ( int i=4; i>0; i--) {
  14. for ( int j=0; j<4; j++) {
  15. petlja[j] = arr[i];
  16. }
  17. }
  18. System.out.println(Arrays.toString(petlja));
  19. }
  20. }
英文:

I was wondering if you can help me around this code. It should reverse content of array but I get this. Does anyone know how to fix this?

  1. import java.util.Arrays;
  2. public class Arrays7 {
  3. public static void main(String[] args) {
  4. // Write a Java program to reverse an array of integer values.
  5. int arr[] = { 1, 2, 3, 4, 5};
  6. int petlja[] = { 0, 0, 0, 0, 0 };
  7. /* arr[0] = petlja[4];
  8. arr[1] = petlja[3];
  9. arr[2] = petlja[2];
  10. arr[3] = petlja[1];
  11. arr[4] = petlja[0];
  12. */
  13. for ( int i=4; i&gt;0; i--) {
  14. for ( int j=0; j&lt;4; j++) {
  15. petlja[j] = arr[i];
  16. }
  17. }
  18. System.out.println(Arrays.toString(petlja));

答案1

得分: 1

你不需要嵌套循环 - 只需要一个循环来遍历数组,并将每个元素赋值给相应的“反转”数组:

  1. for (int i = arr.length - 1; i >= 0; i--) {
  2. petlja[petlja.length - i] = arr[i];
  3. }
英文:

You don't need a nested loop - you need only one loop to go over the array and assign each element to the corresponding "reversed" array:

  1. for (int i = arr.length - 1; i &gt;= 0; i--) {
  2. petlja[petlja.length - i] = arr[i];
  3. }

答案2

得分: 0

你可以这样做:

  1. for(int i = 0; i < array.length; i++) {
  2. petlja[i] = arr[array.length-i-1];
  3. }

示例输入/输出

输入

  1. 1, 2, 3, 4, 5

输出

  1. 5, 4, 3, 2, 1
英文:

You can do it like so:

  1. for(int i = 0; i &lt; array.length; i++) {
  2. petlja[i] = arr[array.length-i-1];
  3. }

Sample I/O

Input

  1. 1, 2, 3, 4, 5

Output

  1. 5, 4, 3, 2, 1

huangapple
  • 本文由 发表于 2020年9月26日 03:36:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64070375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定