import java.util.Scanner;
public class Assign58{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int numintegers, j;
System.out.print("Enter a positive integer: ");
numintegers = keyboard.nextInt();
System.out.print("Now enter " + numintegers + " integers: ");
int[] integers = new int[numintegers];
for (int i=0; i < integers.length; i++){
integers[i] = keyboard.nextInt();
int[] reverse = new int[integers.length];
for (i = 0, j = reverse.length - 1; i < reverse.length; i++, j--){
reverse[j] = integers[i];
}
}
System.out.print("In reverse: ");
for (int i=0; i < integers.length; i++)
System.out.print(integers[i] + " ");
}
}
因此,如果整数为3 4 6 2 9
,我将如何从上面的代码中更改以下内容:
for (int i=0; i < integers.length; i++)
System.out.print(integers[i] + " ");
使输出结果为:
9 - 2 - 6 - 4 - 3
请记住,我需要它以相反的顺序出现,我希望这些数字之间有破折号,并且在最后一个数字之后应该没有破折号。
我希望有人可以帮助我!谢谢!
答案 0 :(得分:1)
使用此代码以相反的顺序打印数组。
int j = integers.length; //integers is the array in which the values are stored.
for(int k=j-1; k>=0; k--)
System.out.print(integers[k]+"-");
答案 1 :(得分:0)
反转for循环以获得相反的顺序
for (int i=integers.length-1; i>=0 i--)
System.out.print(integers[i] + "-");
答案 2 :(得分:0)
for (int i = integers.length; i > 0; i--) {
System.out.print(integers[i] + " - ");
}
System.out.print(integers[0]);
答案 3 :(得分:0)
这应该有效
for (int i=0; i < integers.length; i++){
integers[i] = keyboard.nextInt();
int[] reverse = new int[integers.length];
for (i = 0, j = reverse.length - 1; i < reverse.length; i++, j--){
reverse[i] = integers[j]+" ";
}
}
答案 4 :(得分:0)
System.out.print(reverse[0]);
for (int i=1; i < integers.length; i++)
System.out.print(" - " + reverse[i]);
其他提议的解决方案会打印一个-
太多。
答案 5 :(得分:0)
你可以从最后遍历数组
for(int i = integers.length-1; i >= 0; i--) {
System.out.print(integers[i] + " ");
}
或者您可以使用Stack<Integer>
来推送所有输入的数字,然后按相反的顺序弹出它们。
Stack<Integer> integers = new Stack<Integer>();
for (int i=0; i < numIntegers; i++){
integers.push(keyboard.nextInt());
}
System.out.print("In reverse: ");
while(!integers.isEmpty()) {
System.out.print(integers.pop() + " ");
}