public static void main(String[] args) {
int[] HwArray = new int[10];
int count = 0;
String separate = "";
for (int i = 0; i < HwArray.length; i++) {
System.out.print(separate);
//Generate random numbers
HwArray[i] = (int) (100 + Math.random() * 100);
System.out.println("HwArray[" + i + "]=" + HwArray[i]);
}
int location = linearSearch(HwArray, 150);
System.out.println("\nLinear Search Result: " + location);
}
// Reverse the order of all elements, then print HwArray.
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
System.out.println("HwArray[" + i + "]=" + result[j]);
}
return result;
}
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++) {
if (list[i] == key)
return i; //return the index location
}
return -1; //return if number is not found in the index
}
我正在尝试打印反向中的元素,但它只打印出元素。我不确定是什么问题。
答案 0 :(得分:0)
在提问之前请先研究一下,也许google&#34; java reverse array&#34;。这就是我所做的,并发现这个人问同样的事情。 Reversing an Array in Java
解决方案很简单:
List<Integer> lst = Arrays.asList(list); //Converts the int "list" into a list.
Collections.reverse(lst); //Reverses the list.
result = list.toArray(lst);