创建一个循环,达到末端然后反向返回。

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

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 &lt; arrayNumber.length; ) {
		    if (i &lt; 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&gt;=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

huangapple
  • 本文由 发表于 2020年9月4日 15:39:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63736846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定