【问题标题】:how to use goto in java如何在java中使用goto
【发布时间】:2015-10-11 03:36:21
【问题描述】:
StartAgain:
    if(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
            goto StartAgain;
        }
    }

如果数组列表中的最后两个元素相同并且我想重新生成一个随机数 该列表中包含超过 2 个元素。它不是使用中断/继续的循环。那么我该如何实现呢?

【问题讨论】:

标签: java arraylist goto


【解决方案1】:

这是一个糟糕的设计决定,但您可以在 Java 中使用 lableled statements。在您的情况下,您可能使用

continue StartAgain;

但是你真的应该重新设计你的方法。 14.7 的 JLS 链接(部分)说,

与 C 和 C++ 不同,Java 编程语言没有goto 语句;标识符语句标签与出现在标签语句中的任何位置的break (§14.15) 或continue (§14.16) 语句一起使用。

【讨论】:

  • 我试过了,但我得到了“不能在循环中使用继续”错误?
  • 什么版本的Java?此外,没有任何版本的 Java 具有 goto
  • java 版本 1.8.0_51
【解决方案2】:
    for(bool again = nit_arr.size() > 2; again;)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else{
             again = false;
             // do other stuff if needed
        }
    }

这就是我们可以实现它的方法,以及大多数其他结构,而不需要 goto 语句。即使在 C/C++ 中,通常也不推荐使用 Goto,因为它破坏了代码的结构并使其更难跟踪(由人类)。当然,编译版本中的所有内容都会被翻译成 goto、跳转等。

另一种使用break的方式;稍微不推荐,但还可以:

    while(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else break;
    }

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 2021-07-02
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多