英文:
Create a loop that reaches end then reverses back
问题
我正在尝试创建一个循环,打印数字1、2、3、4、5、6、7、8。一旦到达末尾,循环应该从8、7、6、5、4、3、2、1开始反向。输出只会遍历元素然后结束,不会反向。是否有更好的编程方法,我对编程、数组和循环的使用都相对陌生。任何帮助将不胜感激。
int num = 0;
int[] arrayNumber = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i = 0; i < arrayNumber.length * 2 - 1; i++) {
if (i < 8) {
num = arrayNumber[i];
} else {
num = arrayNumber[arrayNumber.length * 2 - i - 2];
}
System.out.print(num);
}
英文:
I am trying to create a for loop that prints numbers 1, 2, 3, 4, 5, 6, 7, 8. Once reaching the end the loop should reverse back starting from 8, 7, 6, 5, 4, 3, 2, 1. The output only goes through the elements and then ends, it doesn't reverse back. Is there a better way to code this, I am fairly new to programming and working with arrays and loops. Any help will be appreciated.
int num = 0;
int[] arrayNumber = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i = 0; i < arrayNumber.length; ) {
if (i < 8) {
i++;
} else {
i--;
}
num = arrayNumber[i];
System.out.print(num);
}
答案1
得分: 1
你可以为每个显示使用两个循环,如下所示:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
// 第一个用于正向显示
for (int n : numbers) {
System.out.println(n);
}
// 第二个用于反向显示
for (int i = (numbers.length - 1); i >= 0; i--) {
System.out.println(numbers[i]);
}
英文:
You can use 2 Loops for each display like this below:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
//this one fo
for (int n: numbers) {
System.out.println(n);
}
//this one for the Reverse display
for(int i = (numbers.length-1); i>=0;i--){
System.out.println(numbers[i]);
}
答案2
得分: 1
如果你想要创建一个无限循环(在Python中):
i = 0
test = [1, 2, 3, 4, 5, 6, 7, 8]
goesdown = False
while True:
print(test[i])
i += -1 if goesdown == True else 1
if test[i] == test[-1]:
goesdown = True
if test[i] == test[0]:
goesdown = False
英文:
if you want to do an infinite loop (in python) :
i = 0;
test = [1, 2, 3, 4, 5, 6, 7, 8]
goesdown = False
while True:
print(test[i])
i += -1 if goesdown == True else 1
if(test[i] == test[-1]):
goesdown = True
if(test[i] == test[0]):
goesdown = False
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论