gpt4 book ai didi

java - 反向打印数组中的值

转载 作者:行者123 更新时间:2023-12-01 13:28:31 24 4
gpt4 key购买 nike

我的代码旨在打印数组中的值(如果按顺序排列,然后按相反顺序排列)。但是,在编写方法时,我还必须至少使用以下方法 header :

public static int printOriginalArray(int[] list)
public static int printInReverse(int[] list)

我已经运行了代码!我现在明白了!它只是点击!是的!!! :-) 现在我的方法虽然正确但并不完全准确?我应该有 2 个方法而不是 1 个,并且我需要重写它,以便它反转数字,而不是交换。

public class Assignment01a {
public static void main (String[] args) {

int[] numbers = {4, 5, 6, 7};
System.out.println("The list in order is: ");

for (int num: numbers)
System.out.println(num + " ");

swap(numbers, 0, 3);

for (int num: numbers)
System.out.println(num + " ");
}

public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr [i] = arr [j];
arr [j] = temp;
}
}

最佳答案

首先,所有方法都需要在某个类中声明。在这里,您的 swap 方法在 Assignment01a 类中声明。此外,还有静态方法,它们是通过在 public 关键字后面添加 static 关键字来声明的(就像您的 swap 方法一样)。静态方法可以直接从 main() 调用(从“静态上下文”)。然而,非静态方法需要在对象实例上调用/从对象实例调用。这些是没有 static 关键字的方法,可以将它们视为属于特定对象。

关于java - 反向打印数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com