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

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

Reverse array with for loop in Java

问题

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

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

import java.util.Arrays;

public class Arrays7 {

    public static void main(String[] args) {
        // 编写一个Java程序来颠倒整数值的数组。
        
        int arr[] = { 1, 2, 3, 4, 5};
        int petlja[] = { 0, 0, 0, 0, 0 };		
        
        /* arr[0] = petlja[4];
        arr[1] = petlja[3];
        arr[2] = petlja[2];
        arr[3] = petlja[1];
        arr[4] = petlja[0];
        */
        
        for ( int i=4; i>0; i--) {
            for ( int j=0; j<4; j++) {
                petlja[j] = arr[i];
            }
        }
        
        System.out.println(Arrays.toString(petlja));
    }
}
英文:

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?

import java.util.Arrays;

public class Arrays7 {

	public static void main(String[] args) {
		// Write a Java program to reverse an array of integer values.
		
		int arr[] = { 1, 2, 3, 4, 5};
		int petlja[] = { 0, 0, 0, 0, 0 };		
		
		 /* arr[0] = petlja[4];
		arr[1] = petlja[3];
		arr[2] = petlja[2];
		arr[3] = petlja[1];
		arr[4] = petlja[0];
		*/
		
		for ( int i=4; i&gt;0; i--) {
			for ( int j=0; j&lt;4; j++) {
				petlja[j] = arr[i];
			}
		}
		
		System.out.println(Arrays.toString(petlja));

答案1

得分: 1

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

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

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:

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

答案2

得分: 0

你可以这样做:

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

示例输入/输出

输入

1, 2, 3, 4, 5

输出

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

You can do it like so:

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

Sample I/O

Input

1, 2, 3, 4, 5

Output

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:

确定