【问题标题】:How to use goto-like functionality in Processing?如何在处理中使用类似 goto 的功能?
【发布时间】:2014-12-12 04:01:32
【问题描述】:

我正在可汗学院学习编码。它使用处理作为其基本语言。我了解到 Java 没有 goto 功能。那么如何使用处理实现goto功能。使用 sn-p 进行解释表示赞赏。

这是我的代码,我已经评论了我想使用 goto 功能的地方:

/* Returns either the index of the location in the array,
  or -1 if the array did not contain the targetValue */

var doSearch = function(array, targetValue) {
    var min = 0;
    var max = array.length - 1;
    var guess;

    //startover:

    if (guess === max || guess === min) {
      //goto notFound;
    }

    guess = round((min + max) / 2);

    if (targetValue === array[guess]) {
      return guess;
    } else {
      if (targetValue > array[guess]) {
        min = guess + 1;
        //goto startover;
      } else {
        max = guess - 1;
        //goto startover;
      }
    }
  }
  //notFound:
return -1;
};

var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
  41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
];

var result = doSearch(primes, 73);
println("Found prime at index " + result);

//Program.assertEqual(doSearch(primes, 73), 20);

【问题讨论】:

  • 不要使用 goto。它杀死了执行流程,效率极低,不可读drdobbs.com/jvm/programming-with-reason-why-is-goto-bad/…
  • 最好询问您的特定问题或想法,而不是询问不存在的语言功能。处理基于 Java,两者都没有 goto,因为它们是结构化语言。也许通过一些处理教程工作? processing.org/tutorials
  • 我用 C++ 编码已经有十多年了。我唯一一次看到goto 以实际需要goto 的方式使用是在由 YACC 或 BISON 自动生成的解析器代码中。开发人员几乎普遍同意goto 不值得它引起的问题,而且几乎总是应该避免。
  • 为什么不直接使用数组原型“indexOf”developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: processing khan-academy


【解决方案1】:

您可能做的最好的事情是使用 for 循环并将breakcontinue 用于gotos。

for(var unusedVariable = 0;1==1;unusedVariable++){//equivalent of "startover:"
    if(condition1){
        continue;//goto startover;
    }
    if(condition2){
        continue;//goto startover;
    }
    if(condition1){
        break;//goto notFound;
    }
}//notFound:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多